This is a boilerplate for custom element build with svelte. I have some additional code to demonstrate how to use dispatch events cause that varies based on the normal compile to custom element. You can see the "Clean" Section below on how to remove those code.
git clone <your repo url>
npm install
npm run dev
the app should be running in port 5000/rollup.config.js
In Rollup set the custome Element to true,
This will compile to custom element not for SPA, the output will be one JS file stored in either dist or build
customElement: true
/public/index.html
<script defer src='/build/bundle.js'></script>
<hello-component></hello-component>
/src/main.js
<hello-world></hello-world>
to import in the public/index.html
file export { default as App } from "./App.svelte";
/package.json
dist
to convert the svelte file to one single js file and store it in the /dist/index.js
Which can be pushed to github. "dist": "rollup -c -o dist/index.js"
I have some additional code to demonstrate, how to dispatch the event from a web component and listen to that event in the site.
Svelte have an issue dispatching an event for custom elemnt, you can read more about it here.
Svelte is aware of that and working on it.
but for now we have a work around thanks to "TehShrike" .so, instead of dispatching the event like this
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
dispatch("eventName", "event optional data");
We have to do this in custom element.
import { createEventDispatcher } from "svelte";
import { get_current_component } from "svelte/internal";
const component = get_current_component();
const svelteDispatch = createEventDispatcher();
const dispatch = (name, detail) => {
svelteDispatch(name, detail);
component.dispatchEvent &&
component.dispatchEvent(new CustomEvent(name, { detail }));
};
dispatch("eventName", "event optional data");
if you want to clean up this code, follow Clean up instruction below.
Let's remove the demonstration code. so, you can write your own.
/src/SubComponent.svelte
file/public/index.html
/src/App.svelte
except this line<svelte:options tag="hello-component" />
Hope this is useful, Happy coding