close

Svelte

In this document, you will learn how to build a Svelte component library using Rslib. You can check out Svelte related example projects in Examples.

Create Svelte project

You can use create-rslib to create a project with Rslib + Svelte. Just execute the following command:

npm
yarn
pnpm
bun
npm create rslib@latest

Then select Svelte when prompted to "Select template".

Use Rslib in an existing project

For developing Svelte components, you need to set the target to "web" in rslib.config.ts. This is crucial because Rslib sets target to "node" by default, which is different from Rsbuild's default target value.

To compile Svelte (.svelte files), you need to register the @rsbuild/plugin-svelte plugin. This plugin integrates svelte-loader internally and will automatically add the necessary configurations for Svelte build.

For example, register in rslib.config.ts:

rslib.config.ts
import { defineConfig } from '@rslib/core';
import { pluginSvelte } from '@rsbuild/plugin-svelte'; 

export default defineConfig({
  lib: [
    // ...
  ],
  output: {
    target: 'web',
  },
  plugins: [pluginSvelte(/** options here */)],
});

For more configuration options, refer to the @rsbuild/plugin-svelte documentation.

Declaration files

Note

Svelte declaration files are generated by svelte2tsx, so lib.dts / lib.redirect.dts / lib.banner.dts / lib.footer.dts are not effective in Svelte projects.

Rslib provides a plugin example for generating types in Svelte projects: svelteDtsPlugin. The plugin calls the emitDts method provided by svelte2tsx after build to generate declaration files for .svelte files.

If you create a Svelte TypeScript project with create-rslib, this plugin is already included in the template.

For an existing project, you can use it like this:

rslib.config.ts
import { svelteDtsPlugin } from './scripts/rslib-plugin-svelte-dts';

export default {
  plugins: [svelteDtsPlugin()],
};

svelteDtsPlugin passes the following options through to the svelte2tsx emitDts config:

  • declarationDir: The output directory for declaration files. Defaults to ./dist.
  • libRoot: The source directory to emit declaration files for. Defaults to ./src.
  • tsconfig: The tsconfig path used for declaration generation. Defaults to source.tsconfigPath.
  • svelteShimsPath: The path to the svelte2tsx shims type file. Defaults to svelte2tsx/svelte-shims-v4.d.ts.

If you need type checking, install the svelte-check npm package and add a check command to package.json:

package.json
{
  "scripts": {
    "check": "svelte-check"
  },
  "devDependencies": {
    "svelte-check": "^4.4.8"
  }
}