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:
- I'm getting the name of each component-folder
- The resulting array is then used as
rollupOptions.input
- 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:
- The file size of each built component is near identical
- The output of component B includes a JavaScript import for styles that are used exclusively in component A. It
- 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>