We should have at least three files: 'Widget.svelte', 'rollup.config.js' and 'package.json':
- Our widget
Widget.svelte
:
<script>
export let name;
</script>
<h1>Hello {name}!</h1>
<style>
h1 {color: red;}
</style>
- Our
rollup.config.js
:
import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import { terser } from 'rollup-plugin-terser';
export default {
input: './Widget.svelte',
output: {
format: 'iife',
name: 'MyWidget', // Name of the class we will call on the page
file: 'dist/mywidget.js' // the file which we will include on the page
},
plugins: [
svelte({
emitCss: false // Let's store CSS in JS (no-depends), but you can emit it in separate *.css file too
}),
resolve({
browser: true,
dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/')
}),
commonjs(),
terser()
]
};
- And our
package.json
file:
{
"devDependencies": {
"rollup": "^1.12.0",
"rollup-plugin-commonjs": "^10.0.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-svelte": "^5.0.3",
"rollup-plugin-terser": "^5.1.2",
"svelte": "^3.0.0"
},
"scripts": {
"build": "rollup -c"
}
}
-
Run 'npm i' to install all dependencies.
-
Run 'npm run build' to compile our widget to the single
mywidget.js
file in thedist
directory -
Then you can include that file on any HTML page and it will work.
...
<div id="mywidget"></div>
<script src='mywidget.js'></script>
<script>
new MyWidget({
target: document.getElementById("mywidget"),
props: {
name: 'world'
}
});
</script>
...