sveltekit-components Svelte Themes

Sveltekit Components

SvelteKit-app providing Custom Element to other pages

We have a stand-alone app that is built prerendered and hosted on S3. We would like to use some of the components from this app on other webpages in our ecosystem (as a separate sdk.js-file).

Thus, I have come up with the following two-phase build, where node run build calls build:app (using vite_app.config.ts) and build:sdk (using vite_sdk.config.ts) in sequence.

The SvelteKit app has the following structure:

  • src/routes/+page.svelte imports:
    • src/lib/components/Parent.svelte imports:
      • src/lib/util/prependEnvVar -- a function that uses a var from $env/static/public
      • src/lib/components/Child.svelte

The custom element SDK has the following structure, which can be seen in action via sdk_test.html:

  • build/sdk/sdk.js provides a custom element:
    • src/lib/sdk/MyElement.svelte, imports:
      • src/lib/components/Parent.svelte, including its dependencies as above.

While this setup works, I would prefer a single build run, and there are some issues as desribed below.

Current issues

Svelte does not recognize SvelteKit-style imports from $env/static/public

It makes sense not to import private environment variables in a custom Svelte element, but build-time public ones are practical. I currently handle it by building with SvelteKit first, then aliasing a wrapper around that output in vite_sdk.config.ts.

This works but is fairly hacky, and also means that the SvelteKit app needs to be rebuilt & the wrapper has to be updated when new variables are added.

Svelte does not recognize SvelteKit-style $lib-imports

This is mostly solvable with a general $lib-alias in the vite_sdk.config.ts, but requires specific aliases for files with extensions that are not needed in SvelteKit.

svelte-check complains about the custom element

This happens even with compilerOptions set in svelte.config.ts (note also commented-out section there, which makes no difference), which would be incorrect for the SvelteKit build.

/path/to/sveltekit-components/src/lib/sdk/MyElement.svelte:2:3
Warn: The `customElement` option is used when generating a custom element. Did you forget the `customElement: true` compile option?
https://svelte.dev/e/options_missing_custom_element (svelte)
<svelte:options
  customElement={{
    tag: 'my-element',
    shadow: "none"
  }}
/>

One option is to ignore the entire src/lib/sdk-directory but that could potentially miss other issues.

Top categories

Loading Svelte Themes