Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Building Svelte custom elements will mixup styles and code

$
0
0

My project is a library of Web Components built with Svelte. The idea is to build a separate JavaScript file for each of the components.

I have noticed an odd behavior when building this library and it's my assumption that the reason lies in my Vite config.

vite.config.ts

import { basename, resolve } from 'node:path';import { defineConfig } from 'vite';import { glob } from 'glob';import { kebabCase } from 'change-case';import { svelte } from '@sveltejs/vite-plugin-svelte';const components = (await glob('src/components/*/')).map((path) => basename(path));export default defineConfig({    build: {        rollupOptions: {            input: components.map((component) => `./src/components/${component}/index.ts`),            output: components.map((component) => {                const kebabcase = kebabCase(component);                return {                    format: 'esm',                    entryFileNames: `${kebabcase}/[name].js`,                    chunkFileNames: `${kebabcase}/${kebabcase}-[hash].js`,                };            }),            preserveEntrySignatures: 'strict',        },        sourcemap: true,    },    plugins: [        svelte(}),    ],});

Let me explain:

  1. I'm getting the name of each component-folder
  2. The resulting array is then used as rollupOptions.input
  3. It's also passed to rollupOptions.output where I'm adjusting folder and file names

When I'm looking at the output of my build, I'm noticing a couple of things:

  1. The file size of each built component is near identical
  2. The output of component B includes a JavaScript import for styles that are used exclusively in component A. It
  3. The size of each output file grows with each new component added to the library

So it appears to me there a mis-configuration and I'm wondering how to solve it. Here are some more files that play a part in my setup:

svelte.config.js

import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';export default {    compilerOptions: {        customElement: true    },    preprocess: vitePreprocess(),};

A typical component looks similar to the following:

<svelte:options customElement="my-component" /><!-- Markup --><style lang="scss">    @import './MyComponent.scss';</style>

Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>