Experimental!
Node.js esmodules loader for Svelte, and SvelteKit.
This is primarily intended to be used along with uvu for testing svelte components using esm imports.
npm install --save-dev @jerrythomas/svelte-esm-loader@beta
Add the test script to your package.json
"script": {
"test": "NODE_OPTIONS='--experimental-loader @jerrythomas/svelte-esm-loader' uvu test"
}
{ type: 'module' } in your package.json.import statements in your .js test files.With this, you can:
.svelte componentssvelte/compile.svelte/preprocess and [svelte-preprocess][preprocess]..css files without failure (helpful for testing)..postcss)
will also be no-op imported without failure.import { goto } from $app/navigation, will load successfully as a no-op.import Count from $lib/Count.svelte will import from src/lib/Count.svelteimport { something } from $lib/core will import from src/lib/core/index.js or src/lib/core.jsHere we have a simple Svelte component:
<script>
// Component.svelte -- A simple example Svelte component to test.
import './styles/layout.css'
const star = 'Sun'
</script>
<div>
<strong>{star}</strong>
</div>
<style>
strong {
color: orange;
}
</style>
Node.js will ordinarily fail on the following import, as it doesn't know how to handle .svelte (and the included .css) files:
// Component.test.js -- Test a Svelte component.
import Component from './Component.svelte'
The same code will work successfully if we start Node.js with our loader:
NODE_OPTIONS="--experimental-loader @jerrythomas/svelte-esm-loader" npm run test
Here we have a more complex Svelte component, which requires preprocessing for it's advanced features:
<script>
// Component.svelte -- A complex example Svelte component to test.
// ADD: .postcss import
import './styles/page.postcss'
const star = 'Sun'
</script>
<!-- ADD: <template> tag from svelte-preprocess -->
<template>
<div class="planet">
<strong>{star}</strong>
</div>
</template>
<!-- ADD: postcss w/nesting -->
<style lang="postcss">
.planet {
strong {
color: orange;
}
}
</style>
We'll create a new custom config file to hold our [svelte-preprocess][preprocess] settings:
// svelte-preprocess.config.js -- A custom home for our preprocess settings.
export default {
postcss: true,
}
And now we can have our advanced Svelte component compile correctly:
If you happen to use [SvelteKit][sveltekit], and don't want to repeat the processor settings, you can change your svelte.config.js to pull in the config from our custom file:
// svelte.config.js -- SvelteKit config file.
import sveltePreprocess from 'svelte-preprocess'
const { default: sveltePreprocessConfig } = await import(
resolve('./svelte-preprocess.config.js')
)
export default {
// ...,
preprocess: [
// ...,
sveltePreprocess(sveltePreprocessConfig),
],
}
.json files can be accomplished with experimental node flag --experimental-json-modules..js extension works.index.js exists in the folder.from '$utils/draw.js') works. This relies on svelte.config.js.