Skip to content

Instantly share code, notes, and snippets.

@AlexxNB
Last active April 13, 2024 20:50
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save AlexxNB/ab13267ad2a82a29f5466ec24fe797d5 to your computer and use it in GitHub Desktop.
Save AlexxNB/ab13267ad2a82a29f5466ec24fe797d5 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>
 ...
@diegofranca92
Copy link

hey man, did you manage to change the widget props? I tried but I couldn't.

@elzodxon
Copy link

Hello @diegofranca92, now, I can change props as well.

@elzodxon
Copy link

Thank you, it worked;) I have made my own widget:)

@KarthikeyaGit
Copy link

the build is successful but in browsr it is not showing css.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment