Svelte 94 ๐งก Building Custom Component Libraries with @sveltejs/package
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
| Command | Purpose |
|---|---|
svelte-package -i ./src/lib | Source input directory |
-o ./dist | Output destination |
svelte-check | Verify types before build |
Package.json Keys
| Key | Significance |
|---|---|
peerDependencies | Prevents framework duplicates |
exports | Controls access to sub-components |
types | Points 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Duplicated Svelte | Dependency usage | Move to peerDependencies |
| Broken types | Missing TS config | Run svelte-check |
| CSS leakage | Incorrect scoping | Use component-scoped CSS |
| Version mismatch | No peer range | Use ^ 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
| Item | Value |
|---|---|
| Official Tool | @sveltejs/package |
| Peer Deps | svelte |
| Output | /dist |
| Type safety | .d.ts generation |
| Entry point | exports 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
exportsfield inpackage.jsonto 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-checkbefore 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.
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!