Skip to content

Instantly share code, notes, and snippets.

@Realetive
Forked from AlexxNB/widget.md
Created April 5, 2021 05:10
Show Gist options
  • Save Realetive/775482bab518a6a6df0891e91b82f6a2 to your computer and use it in GitHub Desktop.
Save Realetive/775482bab518a6a6df0891e91b82f6a2 to your computer and use it in GitHub Desktop.
Howto make no-depends widget on Svelte and load it on the page

We should have at least three files: 'Widget.svelte', 'rollup.config.js' and 'package.json':

  1. Our widget Widget.svelte:
<script>
	export let name;
</script>

<h1>Hello {name}!</h1>

<style>
	h1 {color: red;}
</style>
  1. 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()
	]
};
  1. 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"
  }
}
  1. Run 'npm i' to install all dependencies.

  2. Run 'npm run build' to compile our widget to the single mywidget.js file in the dist directory

  3. 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>
 ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment