| | |

Svelte 94 ๐Ÿงก Building Custom Component Libraries with @sveltejs/package

โฑ๏ธ Estimated read: 7 min | |

Building a robust Svelte component library requires more than just writing components; it requires a standardized distribution model that respects modern module formats, ensures type safety, and supports tree-shaking for end-users. The official @sveltejs/package tool is the industry-standard mechanism for transforming raw .svelte, .ts, and .js files into a distribution-ready package. It automates the complex build-time tasks of compiling components into JavaScript, generating TypeScript declaration files, and mapping styles.

This chapter covers the architecture of building a library using the official Svelte packaging tool. We will explore how to configure your library for compatibility, how to manage peer dependencies, and how to structure your exports to ensure that users of your library receive the smallest possible bundle sizes while enjoying a seamless developer experience with type completion.

Key point: @sveltejs/package transforms your source Svelte components into a standardized library format by compiling files at build time, generating .d.ts type definitions, and ensuring your library is tree-shakeable via properly configured exports in your package.json.


Why exists

The standardization of Svelte distributions. Before @sveltejs/package, developers used a variety of custom Rollup or Vite configurations that often resulted in conflicting module formats and broken type definitions.

The automated TypeScript declaration requirement. Generating accurate .d.ts files for Svelte components is historically difficult; this tool automates the process, ensuring consumers get full intellisense without manual labor.

The tree-shaking compatibility mandate. Modern frontend development requires that consumers only include the code they use; the packaging tool enforces folder structures that facilitate efficient bundler-level tree-shaking.

The separation of concerns between build and consumption. Developers need to write in modern Svelte 5+ syntax, but users might be on older build pipelines; the tool handles the necessary transpilation while keeping source maps intact.

The simplified peer dependency management. By formalizing how components are packaged, the tool makes it easier for library authors to signal that they depend on the core Svelte framework without bundling it inside their own library.


a. Configuration and the Packaging Workflow

The packaging process is triggered via svelte-package, usually defined as a build script in your package.json. Unlike standard Vite builds which create an application, the packaging tool creates a “dist” folder designed for npm publication.

// package.json
{
  "scripts": {
    "build": "svelte-package -i ./src/lib -o ./dist",
    "check": "svelte-check"
  }
}

The configuration is largely handled by your svelte.config.js. It is essential that you include the vitePreprocess configuration, as the packaging tool uses these settings to handle TypeScript, SCSS, or other pre-processors before emitting the final JavaScript files.

// svelte.config.js
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';

export default {
  preprocess: vitePreprocess(),
  kit: {
    // Component library configuration
  }
};

When you run the build, the tool maps your source structure to the output folder. If you maintain a /src/lib folder, the contents are processed and placed in /dist while maintaining the exact file structure, which allows consumers to import sub-components directly from your library path.


b. Defining Public and Internal APIs

A crucial aspect of library design is deciding which components are exported to users. You achieve this using the exports field in your package.json, which points to the files generated in your dist folder.

// package.json
{
  "exports": {
    ".": {
      "svelte": "./dist/index.js",
      "types": "./dist/index.d.ts"
    },
    "./Button": {
      "svelte": "./dist/Button.svelte.js",
      "types": "./dist/Button.svelte.d.ts"
    }
  }
}

By explicitly defining these exports, you prevent users from importing internal utilities that might change without warning. The "svelte" condition tells Svelte-aware bundlers to prefer the compiled JS output, while the "types" condition provides the necessary definitions for TypeScript autocomplete.


c. Managing Dependencies and CSS

CSS is a common pain point in library authoring. By default, @sveltejs/package processes CSS as part of the component logic. If you use scoped styles within your .svelte components, the packaging tool will inject them into the generated JS, or produce separate CSS files if configured.

// Managing peer dependencies in package.json
{
  "peerDependencies": {
    "svelte": "^4.0.0 || ^5.0.0"
  }
}

Always mark svelte as a peerDependency. Bundling svelte inside your package will cause errors because the consumer’s application will be running a different instance of the framework than the one inside your library. Furthermore, if your library uses specific UI icons or third-party logic, be intentional about whether those should be bundled (dependencies) or left to the user to provide (peerDependencies).


Complete Example Session

// ============================================
// PART 1: THE SOURCE STRUCTURE
// ============================================
// src/lib/
//   โ”œโ”€โ”€ index.js        (Exports)
//   โ”œโ”€โ”€ Button.svelte   (Component)
//   โ””โ”€โ”€ utils.ts        (Helper)

// ============================================
// PART 2: PACKAGE.JSON EXPORTS
// ============================================
{
  "name": "my-ui-lib",
  "version": "1.0.0",
  "exports": {
    ".": { "svelte": "./dist/index.js", "types": "./dist/index.d.ts" }
  },
  "peerDependencies": { "svelte": "^5.0.0" }
}

// ============================================
// PART 3: BUILD COMMAND
// ============================================
// npx svelte-package -i src/lib -o dist

// ============================================
// PART 4: CONSUMPTION
// ============================================
// import { Button } from 'my-ui-lib';
// <Button />

// ============================================
// PART 5: TYPE GENERATION
// ============================================
// The package tool automatically creates
// dist/index.d.ts from your src/lib/index.js

The session outlines the full lifecycle of a library, from folder structure to the build process and finally to how a user consumes the generated types and components.


Quick Reference

Packaging CLI

CommandPurpose
svelte-package -i ./src/libSource input directory
-o ./distOutput destination
svelte-checkVerify types before build

Package.json Keys

KeySignificance
peerDependenciesPrevents framework duplicates
exportsControls access to sub-components
typesPoints to generated definitions

Best Practices

โœ… Do This:

// Use peerDependencies for Svelte
"peerDependencies": { "svelte": "^5.0.0" }              // โœ…

// Explicitly define exports
"exports": { ".": "./dist/index.js" }                  // โœ…

// Always run svelte-check before publish
"prepublishOnly": "svelte-check"                       // โœ…

// Use barrel files for cleaner imports
export { default as Button } from './Button.svelte';  // โœ…

โŒ Don’t Do This:

// Bundle Svelte core in dependencies
"dependencies": { "svelte": "^5.0.0" }                 // โŒ

// Use absolute paths in build configs
"-i /Users/name/lib"                                   // โŒ

// Forget to export types
// Users won't get autocomplete                       // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Duplicated SvelteDependency usageMove to peerDependencies
Broken typesMissing TS configRun svelte-check
CSS leakageIncorrect scopingUse component-scoped CSS
Version mismatchNo peer rangeUse ^ range syntax

Real-World Examples

1. UI Library Entry

export { default as Card } from './Card.svelte';
export { default as Input } from './Input.svelte';

2. SCSS Preprocessing

// svelte.config.js
preprocess: vitePreprocess({ style: { sass: true } })

3. Handling Types

// types.ts
export type ButtonVariant = 'primary' | 'secondary';

4. Excluding files

# Use .npmignore to exclude tests from dist
*.test.ts

5. Subpath imports

// package.json exports
"./utils": "./dist/utils.js"

6. Dynamic exports

// index.js
export * from './components';

7. Versioning

npm version patch

8. Publishing process

npm publish --access public

9. Debugging build

npx svelte-package --verbose

10. Linting before build

eslint src/lib --fix

Visual

The Packaging Pipeline

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  SRC (svelte, ts, scss)                      โ”‚
โ”‚        โ”‚                                     โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                          โ”‚
โ”‚  โ”‚ svelte-package โ”‚ โ”€โ”€โ–บ Transpile            โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”€โ”€โ–บ Type Gen             โ”‚
โ”‚        โ”‚                                     โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                          โ”‚
โ”‚  โ”‚ DIST FOLDER    โ”‚ โ”€โ”€โ–บ NPM READY            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Dependency Relationship

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  LIBRARY (my-lib)                            โ”‚
โ”‚  peer: svelte โ”€โ”€โ–บ user's local svelte        โ”‚
โ”‚                                              โ”‚
โ”‚  CONSUMER APP                                โ”‚
โ”‚  my-lib โ”€โ”€โ–บ uses consumer's svelte instance  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Export structure

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  package.json (exports)                      โ”‚
โ”‚  . โ”€โ”€โ–บ dist/index.js                         โ”‚
โ”‚  ./Button โ”€โ”€โ–บ dist/Button.svelte.js          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Official Tool@sveltejs/package
Peer Depssvelte
Output/dist
Type safety.d.ts generation
Entry pointexports in package.json

Key takeaways:

  • Standardization is mandatory. Using the official packaging tool prevents the configuration hell that plagues custom build setups and ensures broad compatibility.
  • PeerDependencies are critical. Never bundle the core Svelte framework inside your library; always signal it as a peer dependency to avoid runtime conflicts.
  • Exports control your API surface. Use the exports field in package.json to clearly distinguish between public components and internal helper utilities.
  • Types are a first-class citizen. The packaging tool handles TS generation, but you must ensure your source code is well-typed and validated by svelte-check before publishing.
  • Tree-shaking relies on file structure. Keeping your component folder flat and providing specific entry points allows bundlers to drop code that users don’t need.

Remember: A high-quality component library is a promise of stability to its users. By using @sveltejs/package to enforce structure, providing explicit type definitions, and carefully managing your dependencies, you turn your internal components into a professional-grade asset that others can rely on in their own production environments.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!