How do I exclude files from svelte-kit build? - sveltekit

If I run npm run build with SvelteKit it seems to include all files from the src folder. Is it possible to exclude a certain file type (eg. *test.js)?
Example
Select demo app with npm init svelte#next my-app
Add the following code to src/routes/todos/foo.test.js
describe('foo', () => {
it('temp', () => {
expect(true).toBe(false)
})
})
npm run build
npm run preview
Result: describe is not defined
Workaround
Move tests outside of src

UPDATE: SvelteKit 1.0.0-beta now requires pages/endpoints to follow a specific naming pattern, so explicit file exclusion should no longer be needed.
SvelteKit specially handles files in the routes/ directory with the following filenames (note the leading + in each filename):
+page.svelte
+page.js
+page.server.js
+error.js
+layout.svelte
+layout.js
+layout.server.js
+server.js
All other files are ignored and can be colocated in the routes/ directory.
If, for some reason, you need to have a file that has a special name shown above, it's currently not possible to exclude that file from special processing.
Original outdated answer:
SvelteKit 1.0.0-beta supports a routes configuration that enables file exclusion from the src/routes directory. The config value is a function that receives a file path as an argument, and returns true to use the file as a route.
For example, the following routes config excludes *.test.js files from routes:
// sveltekit.config.js
⋮
const config = {
kit: {
⋮
routes: filepath => {
return ![
// exclude *test.js files
/\.test\.js$/,
// original default config
/(?:(?:^_|\/_)|(?:^\.|\/\.)(?!well-known))/,
].some(regex => regex.test(filepath))
},
},
}
demo

Related

Create React App with TypeScript and NPM Link: Enums causing Module parse failed

I have a basic create-react-app TypeScript project (client). Just directory up, I have a server and a shared folder. Inside the shared folder I have a number of interfaces and enums that I share between the server and the client.
I wish to link this shared folder to both the client and server packages.
First, I went to shared and ran $ yarn link and then ran $ yarn link shared from both the client and the server folders.
The server is as happy as can be, and for the most part the client is too. However, as soon as I use one of the enums from the shared directory in the client, I get an error:
../shared/src/models/Roles.ts 4:0
Module parse failed: The keyword 'enum' is reserved (4:0)
File was processed with these loaders:
* ./node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
You may need an additional loader to handle the result of these loaders.
| $RefreshSetup$(module.id);
|
> enum Roles {
| RW_ORG = "rw_org", // can modifiy organization and it's users, nothing else
I'm importing it like so:
import {Roles} from "shared";
but have tried numerous other ways as well.
I'm exporting it from the shared index.ts like so
import Roles from "./models/Roles";
export type {
// all of my interfaces
};
export { Roles }
All of my interfaces are usable, so I don't understand. What the hell is going on here?
Well, it turns out that these errors are all cause by create-react-app's default webpack.config.js. If you navigate to code node_modules/react-scripts/config/webpack.config.js you fill find a line include: paths.appSrc which basically limits Babel to the src/ folder of the react app itself.
That means, if you've yarn linked a folder outside of it, Babel will not transpile it to normal JS, and thus React cannot use it.
There are two hacky solutions, but I would like a better one.
Manually (or via a build script) delete the include: paths.appSrc line from react-scripts every time you install a node module
Make a script that copies the external directory into your React src directory every time the external directory is modified.
I really wish there were an official way around this...
Based on #foxtrotuniform6969's answer, i created a #cracro/craco configuration that gets rid of the misbehaving setting by itself.
module.exports = {
webpack: {
configure: (webpackConfig) => ({
...webpackConfig,
module: {
...webpackConfig.module,
rules: webpackConfig.module.rules.map((rule) => {
if (!rule.oneOf) return rule;
return {
...rule,
oneOf: rule.oneOf.map((ruleObject) => {
if (
!new RegExp(ruleObject.test).test('.ts') ||
!ruleObject.include
)
return ruleObject;
return { ...ruleObject, include: undefined };
}),
};
}),
},
}),
},
};
https://gist.github.com/PhilippMolitor/00f427d12a9c5bca84309058d88846b7
It is possible to automatically remove the include path setting mentioned in the other answer using react-app-rewired.
The following config-overrides.js works for react-scripts:4.0.3 and causes babel to also transpile files in node-modules.
// config-overrides.js
module.exports = function override(config, env) {
// This line might break with other react-script versions
delete config.module.rules[1].oneOf[2].include
return config
}
The other answers to this question suggest removing the include in react-scripts' webpack.config (either with craco or react-app-rewired). I found this worked with yarn start, but when I made a production build with yarn build I got the error Uncaught ReferenceError: exports is not defined at runtime.
Instead of removing the include, I had to add the other project's src in addition to the existing src directory.
Here's my config-overrides.js to be used with react-app-rewired.
For react-scripts 4:
const path = require("path");
module.exports = function override(config) {
// See https://stackoverflow.com/questions/65893787/create-react-app-with-typescript-and-npm-link-enums-causing-module-parse-failed.
config.module.rules[1].oneOf[2].include = [
path.join(__dirname, './src'),
path.join(__dirname, '../backend/src')
];
return config
}
For react-scripts 5:
const path = require("path");
module.exports = function override(config) {
// See https://stackoverflow.com/questions/65893787/create-react-app-with-typescript-and-npm-link-enums-causing-module-parse-failed.
config.module.rules[1].oneOf[3].include = [
path.join(__dirname, './src'),
path.join(__dirname, '../backend/src')
];
return config
}
My craco config, does the same thing as Phil Mo's version as far as I can tell but is easier to understand
module.exports = {
webpack: {
configure: (webpackConfig) => {
webpackConfig.module.rules[0].oneOf.find(
({ test: t }) =>
t != null &&
!Array.isArray(t) &&
t.toString().includes('ts')
).include = undefined
return webpackConfig
}
}
}

TypeScript with Relay: Can't resolve generated module

In my MessageItem.tsx component I have the following code:
const data = useFragment(
graphql`
fragment MessageItem_message on Message {
date
body
}
`,
message as any
);
After running relay-compiler --src ./src --schema ../../schema.graphql --language typescript --artifactDirectory ./src/__generated__, a module named MessageItem_message.graphql.ts gets generated.
But when I run the app it gives me an error:
Failed to compile.
./src/components/MessageItem.tsx
Module not found: Can't resolve
'./__generated__/MessageItem_message.graphql'
The reason is only components at the src root can refer to the right path (./__generated__), whereas components in a folder actually need to refer to the path (../__generated__) but it's not doing so.
How can I configure the path?
Edit .babelrc to point to the artifactDirectory
// .babelrc
{
"plugins": [
[
"relay",
{
"artifactDirectory": "./src/ui/graphql/types"
}
]
]
}
Remove "--artifactDirectory ./src/__generated__" from the relay-compiler options.
By default it seems the Relay compiler puts a "__generated__" directory in the directory with any source code containing GraphQL.
As a result any "./__generated__" references anywhere and at any level in the source code hierarchy now work as they should.
Thanks to #ThibaultBoursier for the pointer.
PS I wonder if the --artifcactDirectory option is just meant to be used to change the name of the artifact directory, rather than its location?
Just moments ago I ran into the same issue. The reason is that the relay-compiler is using the artifactDirectory setting to decide where to put the generated files, but the babel-plugin-relay exposing the graphql tag needs to get the very same argument otherwise it just attempts to include a colocated relative file.
I fixed it in my case by configuring the plugin with a babel-plugin-macros.config.js file as follows (where the artifactDirectory is the same as the one supplied to the relay-compiler):
module.exports = {
relay: {
artifactDirectory: "./src/ui/graphql/types",
},
};
This solution assumes you are using the macro via babel-plugin-macros, otherwise you might need to supply that argument via the .babelrc file but I have no experience with that unfortunately.

How to add static files link on index.html in Vue 2.5?

I tried with following explanation in vue 2.5 it does not work. But in version vue 2.4.2 working fine.
"Real" Static Assets
In comparison, files in static/ are not processed by Webpack at all: they are directly copied to their final destination as-is, with the same filename. You must reference these files using absolute paths, which is determined by joining build.assetsPublicPath and build.assetsSubDirectory in config.js.
As an example, with the following default values:
// config/index.js
module.exports = {
// ...
build: {
assetsPublicPath: '/',
assetsSubDirectory: 'static'
}
}
Any file placed in static/ should be referenced using the absolute URL /static/[filename]. If you change assetSubDirectory to assets, then these URLs will need to be changed to /assets/[filename].
Any suggestion for vue 2.5.2 ?

React Native- How to access .csv files in my project hierarchy

I am trying to load a CSV file in my js class and I am unable to do so in react native. This file is available locally. Not downloaded. Whenever I give a path to the CSV file, I get an error that says The module could not be found. No such module exists. I have tried placing the CSV in various folders and also at my project root level. It does not work. I noticed images do not face the same problem.
I have even tried doing this.
https://willowtreeapps.com/ideas/react-native-tips-and-tricks-2-0-managing-static-assets-with-absolute-paths/
Again it works for images but strangely not for CSVs.
I have tried the import statement, require statement and even relative path for the files. Same error every time.
I am new to react maybe I am missing some step?
EDIT: Two of the ways I tried
import RNFS from 'react-native-fs';
import Papa from 'papaparse';
import CSVData from './CSVData.csv';
function loadAllCSV()
{
console.log('Loading CSV');
var path = './CSVData.csv';
console.log(path);
const fileContents = RNFS.read(path);
console.log('File Data ' + fileContents);
Papa.parse(CSVData, {
download: true,
delimiter: '\t',
complete: function(results) {
console.log('ZOMBIIIIEEEE');
console.log(results);
}
});
}
Error:
Failed to load bundle(http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false) with error:(Unable to resolve module ./CSVData.csv from /Users/abc/xyz/SearchPage.js: The module ./CSVData.csv could not be found from /Users/abc/xyz/SearchPage.js. Indeed, none of these files exist:
/Users/abc/xyz/CSVData.csv(.native||.ios.js|.native.js|.js|.ios.json|.native.json|.json)
/Users/abc/xyz/CSVData.csv/index(.native||.ios.js|.native.js|.js|.ios.json|.native.json|.json) (null))
Adding the .CSV files to the project assets bundle in iOS fixed this problem for me.
Use Xcode to place the files in the project in the Project Settings under the Build Phases Tab check if the Assets are included in the Copy Bundle Resources Section. Add the files to the list here incase they are missing.

Require.js build not concatenation scripts loaded with Jam

Following one of the chapters of "Developing Backbone.js Apllication" by Addy Osmani (O'Reilly) about Grunt-BBB (Backbone Boilerplate Buddy), I just couldn't manage to create a build profile.
Here is the filesystem tree used for this :
/builds
/closure
/rhino
/config
/build.js
build.sh
/development
/* Grunt-BBB files after init */
/app
/styles
index.css
app.js
config.js
main.js
router.js
/test
/* Not important files used for testing */
/vendor
/h5bp
/css
main.css
normalize.css
/jam
/backbone
backbone.js
package.json
/bakbone.layoutmanager
bakbone.layoutmanager.js
package.json
/jquery
jquery.js
package.json
/lodash
lodash.js
lodash.min.js
lodash.underscore.min.js
package.json
require.config.js
require.js
/js
/libs
almond.js
require.js
/distribution
/* Empty dist directory where the optimized / minified / concatenated files should go */
Here are the steps I followed in the /development directory :
1) Install Grunt-BBB (npm install -g bbb)
2) Download r.js, a part of the Require.js project (git clone https://github.com/backbone-boilerplate/grunt-bbb)
3) Initialize the files of the boilerplate (bbb init)
Here is the build.js file I used to configure the r.js AMD loader for the Google Closure compiler :
({
appDir: '../../development',
baseUrl: 'app',
dir: '../../distribution',
optimize: 'closure', // 'uglify2'
paths: {
backbone: '../vendor/jam/backbone/backbone',
'backbone.layoutmanager': '../vendor/jam/backbone.layoutmanager/backbone.layoutmanager',
jquery: '../vendor/jam/jquery/jquery',
lodash: '../vendor/jam/lodash/backbone.min'
},
modules: [
{
name: 'main'
}
],
onBuildRead: function(moduleNames, path, contents) {
return contents;
//return contents.replace(/console\.log\(([^\)]+)\);/g, '')
// .replace(/debugger;/, '');
}
})
and this is the build.sh file I use :
#!/usr/bin/env bash
# r.js directory
RJSDIR="r.js"
RJS="$RJSDIR/dist/r.js"
# Rhino directory
RHINODIR="rhino"
RHINO="$RHINODIR/js.jar"
# Google Closure Compiler directory
CLOSUREDIR="closure"
CLOSURE="$CLOSUREDIR/compiler.jar"
# Build config directory
CONFIGDIR="config"
CONFIG="$CONFIGDIR/build.js"
# Launch compillation
java -Xms256m -Xmx256m -classpath "$RHINO":"$CLOSURE" org.mozilla.javascript.tools.shell.Main "$RJS" -o "$CONFIG" $#
My goal is to optimize, minify, concatenate all the JavaScrit file including the libraries and templates (which I don't have yet, I am only using the boilerplate files) but also CSS files.
The result I get by running ./build.sh is that every files are correctly minimised (besides CSS rule inlining, but that is besides the point) and concatenated but resources that are loaded and managed by the Jam (package manager that combines NPM and Require.js) aren't concatenated.
The reason for that since they are already loaded / managed by Jam, they are not redeclared in the JavaScript files AMD style.
In conclusion, my questions are the following :
How can I rewrite my build.js configuration file so that resources that are loaded by Jam also get included and concatenated in the release / dist file ?
How can I make it so that the concatenated resources aren't copied in the realse / dist directory ? Is it possible to configure this in the build.js file or should this go in my build.sh file ?
Edit : New build.js file :
({
appDir: '../../development',
baseUrl: 'app',
dir: '../../distribution',
optimize: 'closure', // 'uglify2'
paths: {
requirejs : '../vendor/jam/require',
backbone: '../vendor/jam/backbone/backbone',
'backbone.layoutmanager': '../vendor/jam/backbone.layoutmanager/backbone.layoutmanager',
jquery: '../vendor/jam/jquery/jquery',
lodash: '../vendor/jam/lodash/backbone.min'
},
name: 'main',
include: ['requirejs'],
onBuildRead: function(moduleNames, path, contents) {
return contents;
//return contents.replace(/console\.log\(([^\)]+)\);/g, '')
// .replace(/debugger;/, '');
}
})
And here is the error :
file:///vendor/js/libs/require.jsFailed to load resource: The requested URL was not found on this server.
file:///app/styles/index.cssFailed to load resource: The requested URL was not found on this server.
require.js is never included by r.js unless you instruct it to do so. See this link:
http://requirejs.org/docs/optimization.html#onejs
The link refers to command-line options, but the build file options are broadly the same:
you need to define a dummy module for require.js in your paths:
paths: {
requireLib : '/path/to/require.js'
backbone: '../vendor/jam/backbone/backbone',
'backbone.layoutmanager': '../vendor/jam/backbone.layoutmanager/backbone.layoutmanager',
jquery: '../vendor/jam/jquery/jquery',
lodash: '../vendor/jam/lodash/backbone.min'
},
and include it:
name "main",
include: ["requireLib"],
You can ensure that allnested dependencies are resolved by setting:
findNestedDependencies: true,
You can configure an output path using 'out' in your build file
out: "path/to/my/builtfile-1.0.0.js",
Sorry I don't know enough about jam to say whether jam would override this setting
_Pez

Resources