sveltesveltekitsvelte-component

How to compile a Svelte app to a Web Component/Vanilla JS that can be used on external sites?


About a year ago, I created a Vue web component that could be included on any website to facilitate Open Banking payments in the UK. We've even got a WordPress, Magento & Shopify plugins that uses this web component.

You can check out how it works here.

I've re-created the widget in Svelte and used Flowbite Svelte to style it.

I'm however stuck on how to export this out as web component or vanilla JS so that it could be used in exactly the same manner as the Vue version - A single JS file that contains all the functioning code, including Flowbite/CSS and the whole thing contained within a ShadowDOM.

I've seen conflicting guides online where compilerOptions: { customElement: true,} is either set in svelte.config.js, vite.config.js or rollup.config.js.

I was under the impression doing something like this in Svelte would be considerably easier compared to Vue, albeit this did massively help when doing it in Vue.

Someone kindly pointed me to this answer but I'm struggling getting it to work for the following reasons:

I would really appreciate it if someone could point me in the right direction of how to achieve what it is I'm after.

Project Structure

enter image description here

SvelteKit Version of Project Structure

enter image description here


Solution

  • dist/index.js doesn't exist

    Because you are not using SveleKit, this is where it outputs the processed components/code (I even wrote as much in my answer: "This build operates on the output of SvelteKit which is written to dist and creates a separate JS output in dist-js"). Point the build directly to some index file in your source.

    When I run npm run build it generated 4 files in the dist/assets folder: index-DwmGsLQW.js, apexcharts.common.js & index-uK8bMt0h

    The hash in the file path will change every time some content changes, if anything add the package version instead.

    Changed the entry point to index-DwmGsLQW.js and ran vite -c vite.js.config.js build which generated components.js, components.umd.js & apexcharts.common.js in the the dist-js folder

    You don't need a separate build at all (especially not one pointing to a file that will disappear at the slightest change) if you don't use SvelteKit/@sveltejs/package.

    Set up one lib build that points directly to your source if you don't intend to publish the components for native usage in Svelte projects.

    Using this components.js on a plain HTML page is giving me the following error in the console: Unexpected token 'export' (at app_2.js:113050:1)

    It's a module script, so either use the UMD version or set the correct type. (<script type="module" ...>).