Svelte Razor Views - UMD
darren
0 reactions 2022-04-06
Compiling Svelte into UMD bundles.
Svelte in Razor Views using UMD
I’ve been experimenting further with including Svelte in Razor Views. Originally, I was compiling Svelte components to web components. Now, I’ve setup a new project that instead compiles the Svelte files into UMD bundles.
Below is the video where I picked up this technique:
Jesse Skinner - Adding Svelte to your legacy projects
What I prefer about this technique is the ability to set the “target” and props for a Svelte component in the script tag of the Razor Page using the component, rather that including that information as part of the bundle.
<script src="~/js/build/App.js"></script>
<script>
const app = document.querySelector('#app');
app.innerHTML='';
new App({
target: app,
props: {name: 'World', id: 'world'}
})
</script>
Here is the new rollup config. Note that instead of a bundle containing all the Svelte components, I’m passing an argument to create a separate JavaScript file for each Svelte component.
import svelte from 'rollup-plugin-svelte';
import resolve from '@rollup/plugin-node-resolve';
import css from 'rollup-plugin-css-only';
export default {
// each svelte component is built into a js and css file
input: `wwwroot/js/${process.env.entry}.svelte`,
output: {
sourcemap: true,
file: `wwwroot/js/build/${process.env.entry}.js`,
format: 'umd',
name: process.env.entry,
},
plugins: [
svelte({
// Tell the svelte plugin where our svelte files are located
include: 'wwwroot/**/*.svelte',
}),
css({ output: `${process.env.entry}.css` }),
resolve({
browser: true,
dedupe: ["svelte"]
}),
]
};
For the build script, I’m calling rollup once per Svelte component
"scripts": {
"build": "rollup -c rollup.config.js --environment entry:Checklist && rollup -c rollup.config.js --environment entry:App",
"dev": "rollup -c rollup.config.js -w --environment entry:Checklist && rollup -c rollup.config.js -w --environment entry:App"
},
Next Steps
- Improvements to development, having Svelte files and CSS changes appear immediately in browser.
- A script to call rollup for each .svelte file in the JS folder, rather than manually adding calls to build script.
- Experimenting with fetching to the ASP.Net controller from the Svelte component