This is the developer documentation for Svelte CLI.
# Overview
コマンドラインインターフェイス(CLI)である`sv`は、Svelteアプリケーションの作成と管理のためのツールキットです。
## 使用方法
`sv`を実行する最も簡単な方法は、[`npx`](https://docs.npmjs.com/cli/v8/commands/npx)(または他のパッケージマネージャを使用している場合は同等のコマンド - 例えば、[pnpm](https://pnpm.io/)を使用している場合は`pnpm dlx`)を使うことです:
```sh
npx sv
```
既に`sv`がインストールされているプロジェクトの内部にいる場合は、ローカルインストールを使用します。それ以外の場合は最新バージョンをダウンロードしてインストール無しで実行します。これは特に[`sv create`](sv-create)に便利です。
## 謝辞
npmで元々`sv`という名前を所有していた[Christopher Brown](https://github.com/chbrown)に感謝いたします。彼のおかげで、この名前がSvelte CLIのために使えるようになりました。元の`sv`パッケージは[`@chbrown/sv`](https://www.npmjs.com/package/@chbrown/sv)で見つけることができます。
# Frequently asked questions
## How do I run the `sv` CLI?
Running `sv` looks slightly different for each package manager. Here is a list of the most common commands:
- **npm** : `npx sv create`
- **pnpm** : `pnpm dlx sv create`
- **Bun** : `bunx sv create`
- **Deno** : `deno run npm:sv create`
- **Yarn** : `yarn dlx sv create`
## `npx sv` is not working
Some package managers prefer to run locally installed tools instead of downloading and executing packages from the registry. This issue mostly occurs with `npm` and `yarn`. This usually results in an error message or looks like the command you were trying to execute did not do anything.
Here is a list of issues with possible solutions that users have encountered in the past:
- [`npx sv` create does nothing](https://github.com/sveltejs/cli/issues/472)
- [`sv` command name collides with `runit`](https://github.com/sveltejs/cli/issues/259)
- [`sv` in windows powershell conflicts with `Set-Variable`](https://github.com/sveltejs/cli/issues/317)
# sv create
`sv create`は、[追加機能の設定](sv-add#Official-add-ons)オプションを含む新しいSvelteKitプロジェクトをセットアップします。
## 使用方法
```sh
npx sv create [options] [path]
```
## オプション
### `--from-playground `
Create a SvelteKit project from a [playground](/playground) URL. This downloads all playground files, detects external dependencies, and sets up a complete SvelteKit project structure with everything ready to go.
Example:
```sh
npx sv create --from-playground="https://svelte.dev/playground/hello-world"
```
### `--template `
使用するプロジェクトテンプレート:
- `minimal` — 新しいアプリのための最小限のスキャフォールディング
- `demo` — JavaScript無しで動作するワード推測ゲームを備えたデモアプリ
- `library` — Svelteライブラリのためのテンプレートで、`svelte-package`でセットアップされています
### `--types `
プロジェクトに型チェックを追加するかどうか、またその方法:
- `ts` — `.ts`ファイルをデフォルトとし、`.svelte`コンポーネントに対して`lang="ts"`を使用
- `jsdoc` — [JSDoc構文](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html)を使用して型を記述
### `--no-types`
型チェックの追加を防ぎます。推奨されません!
### `--add [add-ons...]`
Add add-ons to the project in the `create` command. Following the same format as [sv add](sv-add#Usage).
Example:
```sh
npx sv create --add eslint prettier [path]
```
### `--no-add-ons`
対話型のアドオンプロンプト無しでコマンドを実行
### `--install `
パッケージマネージャーを指定して依存関係(dependencies) のインストールを行います:
- `npm`
- `pnpm`
- `yarn`
- `bun`
- `deno`
### `--no-install`
依存関係のインストールを行いません。
### `--no-dir-check`
Skip checking whether the target directory is empty.
# sv add
`sv add`は、既存のプロジェクトに新しい機能を追加するコマンドです。
## 使用方法
```sh
npx sv add
```
```sh
npx sv add [add-ons]
```
スペースで区切った複数のアドオンを[以下のリスト](#Official-add-ons)から選択するか、対話型プロンプトを使用することができます。
## オプション
### `-C`, `--cwd`
Path to the root of your Svelte(Kit) project.
### `--no-git-check`
Even if some files are dirty, no prompt will be shown
### `--no-download-check`
Skip all download confirmation prompts
> [!IMPORTANT]
> Svelte maintainers have not reviewed community add-ons for malicious code. Use at your discretion
### `--install `
Installs dependencies with a specified package manager:
- `npm`
- `pnpm`
- `yarn`
- `bun`
- `deno`
### `--no-install`
Prevents installing dependencies
## 公式アドオン
- [`better-auth`](better-auth)
- [`drizzle`](drizzle)
- [`eslint`](eslint)
- [`mcp`](mcp)
- [`mdsvex`](mdsvex)
- [`paraglide`](paraglide)
- [`playwright`](playwright)
- [`prettier`](prettier)
- [`storybook`](storybook)
- [`sveltekit-adapter`](sveltekit-adapter)
- [`tailwindcss`](tailwind)
- [`vitest`](vitest)
## Community add-ons
> [!NOTE]
> Community add-ons are currently **experimental**. The API may change. Don't use them in production yet!
> [!NOTE]
> Svelte maintainers have not reviewed community add-ons for malicious code!
Community add-ons are npm packages published by the community. Look out for add-ons from your favourite libraries and tools. _(soon)_ Many developers are building `sv` add-ons to make their integrations a one-liner. You can find them on [npmx](https://www.npmx.dev/search?q=keyword:sv-add) by searching for the keyword: `sv-add`.
```sh
# Install a community add-on by org name (it will look at @org/sv)
npx sv add @supacool
# Use a local add-on (for development or internal use)
npx sv add file:../path/to/my-addon
# Mix and match official and community add-ons
npx sv add eslint @supacool
# Also works when creating a new project directly
npx sv create --add eslint @supacool
```
> [!NOTE]
> On Windows PowerShell, `@` is a special character that should be escaped with single quotes. For example: `npx sv add '@supacool'`.
Want to create your own? Check the [Add-on Docs](community).
# sv check
`sv check`は、プロジェクト内の次のようなエラーや警告を見つけます:
- 未使用のCSS
- アクセシビリティのヒント
- JavaScript/TypeScriptコンパイラエラー
Node 16以降が必要です。
## インストール
プロジェクトに`svelte-check`パッケージをインストールする必要があります:
```sh
npm i -D svelte-check
```
## 使用方法
```sh
npx sv check
```
## オプション
### `--workspace `
ワークスペースへのパス。`node_modules`と`--ignore`で指定したディレクトリ以外のすべてのサブディレクトリがチェックされます。
### `--output `
エラーや警告の表示方法。詳細は[機械可読出力](#Machine-readable-output)を参照してください。
- `human`
- `human-verbose`
- `machine`
- `machine-verbose`
### `--watch`
プロセスを生存させ、変更を監視します。
### `--preserveWatchOutput`
ウォッチモードで画面がクリアされるのを防ぎます。
### `--tsconfig `
`tsconfig`または`jsconfig`ファイルへのパスを指定します。パスはワークスペースパスからの相対パスまたは絶対パスにすることができます。これを行うことで、設定ファイルの`files`/`include`/`exclude`パターンに一致したファイルのみに診断が適用されます。また、TypeScript および JavaScript ファイルからのエラーが報告されます。指定されていない場合は、プロジェクトディレクトリから上方に`jsconfig`/`tsconfig.json`ファイルを探します。
### `--no-tsconfig`
現在のディレクトリとその下にあるSvelteファイルのみをチェックし、`.js`/`.ts`ファイルを無視したい場合に使用します(型チェックされません)。
### `--ignore `
ワークスペースのルートから相対的に無視するファイルやフォルダ。パスはカンマで区切り、引用符で囲む必要があります。例:
```sh
npx sv check --ignore "dist,build"
```
`--no-tsconfig`と併用した場合にのみ効果があります。`--tsconfig`と併用した場合、診断されるファイルではなくウォッチされたファイルにのみ影響します。その診断は`tsconfig.json`によって決定されます。
### `--fail-on-warnings`
指定された場合、警告があると`sv check`はエラーコードで終了します。
### `--compiler-warnings `
`code`が[コンパイラ警告コード](../svelte/compiler-warnings)で、`behaviour`が`ignore`または`error`である`code:behaviour`ペアのリスト。例:
```sh
npx sv check --compiler-warnings "css_unused_selector:ignore,a11y_missing_attribute:error"
```
### `--diagnostic-sources `
コード診断を実行するソースのリストをカンマで区切って引用符で囲みます。デフォルトではすべてアクティブです:
- `js` (TypeScriptを含む)
- `svelte`
- `css`
例:
```sh
npx sv check --diagnostic-sources "js,svelte"
```
### `--threshold `
診断をフィルタリングします:
- `warning` (デフォルト) — エラーと警告の両方が表示されます
- `error` — エラーのみが表示されます
## トラブルシューティング
プリプロセッサのセットアップやその他のトラブルシューティングについては、[言語ツールのドキュメント](https://github.com/sveltejs/language-tools/blob/master/docs/README.md)を参照してください。
## マシンリーダブル向け出力
`--output`を`machine`または`machine-verbose`に設定すると、CIパイプライン内やコード品質チェックなどで機械によって読みやすい形式で出力がフォーマットされます。
各行は新しいレコードに対応しています。行は一つのスペース文字で区切られた列で構成されます。各行の最初の列はミリ秒のタイムスタンプを含み、モニタリング目的で使用できます。第二列は"行タイプ"を示し、それに基づいて後続の列の数とタイプが異なる場合があります。
最初の行は`START`タイプで、ワークスペースフォルダを含みます(引用符で囲まれています)。例:
```
1590680325583 START "/home/user/language-tools/packages/language-server/test/plugins/typescript/testfiles"
```
`ERROR`または`WARNING`レコードが続く場合があります。それらの構造は出力の引数によって異なります。
引数が`machine`の場合、ファイル名、開始行および列番号、エラーメッセージが示されます。ファイル名はワークスペースディレクトリ相対です。ファイル名とメッセージはどちらも引用符で囲まれています。例:
```
1590680326283 ERROR "codeactions.svelte" 1:16 "Cannot find module 'blubb' or its corresponding type declarations."
1590680326778 WARNING "imported-file.svelte" 0:37 "Component has unused export property 'prop'. If it is for external reference only, please consider using `export const prop`"
```
引数が`machine-verbose`の場合、ファイル名、開始行と列番号、終了行と列番号、エラーメッセージ、診断コード、コードの人間が読みやすい説明、診断の人間が読みやすいソース(例:svelte/typescript)が示されます。ファイル名はワークスペースディレクトリ相対です。各診断はタイムスタンプでプレフィックスされた[ndjson](https://en.wikipedia.org/wiki/JSON_streaming#Newline-Delimited_JSON)行として表されます。例:
```
1590680326283 {"type":"ERROR","fn":"codeaction.svelte","start":{"line":1,"character":16},"end":{"line":1,"character":23},"message":"Cannot find module 'blubb' or its corresponding type declarations.","code":2307,"source":"js"}
1590680326778 {"type":"WARNING","filename":"imported-file.svelte","start":{"line":0,"character":37},"end":{"line":0,"character":51},"message":"Component has unused export property 'prop'. If it is for external reference only, please consider using `export
const prop`","code":"unused-export-let","source":"svelte"}
```
出力は、チェック中に遭遇したファイル、エラー、および警告の合計数を要約する`COMPLETED`メッセージで終了します。例:
```
1590680326807 COMPLETED 20 FILES 21 ERRORS 1 WARNINGS 3 FILES_WITH_PROBLEMS
```
ランタイムエラーが発生した場合、このエラーは`FAILURE`レコードとして表示されます。例:
```
1590680328921 FAILURE "Connection closed"
```
## クレジット
- `svelte-check`の基礎を築いたVueの[VTI](https://github.com/vuejs/vetur/tree/master/vti)
## よくある質問 (FAQ)
### なぜ特定のファイル(たとえばステージングされたファイルのみ)をチェックするオプションがないのですか?
`svelte-check`は、チェックが有効になるためにプロジェクト全体を「見る」必要があります。例えば、コンポーネントプロパティの名前を変更しましたが、そのプロパティが使用されている場所の更新を忘れた場合、使用サイトはすべてエラーになりますが、変更されたファイルのみをチェックするとこれらを見逃すことになります。
# sv migrate
`sv migrate`は、Svelte(Kit)のコードベースを移行します。このコマンドは[`svelte-migrate`](https://www.npmjs.com/package/svelte-migrate)パッケージに委譲されています。
一部のマイグレーションでは、完了するべきタスクをコードベースに注釈として付け加えることがあります。`@migration`で検索することでそれらを見つけることができます。
## 使用方法
```sh
npx sv migrate
```
You can also specify a migration directly via the CLI:
```sh
npx sv migrate [migration]
```
## マイグレーション
### `app-state`
`.svelte`ファイル内で使用されている`$app/stores`を`$app/state`に移行します。詳細は[マイグレーションガイド](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated)を参照してください。
### `svelte-5`
Svelte 4アプリをSvelte 5にアップグレードし、個々のコンポーネントを[runes](../svelte/what-are-runes)やその他のSvelte 5の構文に更新します([マイグレーションガイドを参照](../svelte/v5-migration-guide))。
### `self-closing-tags`
`.svelte`ファイル内のすべての自己終了要素以外の要素を置換します。詳細は[プルリクエスト](https://github.com/sveltejs/kit/pull/12128)を参照してください。
### `svelte-4`
Svelte 3アプリをSvelte 4にアップグレードします([マイグレーションガイドを参照](../svelte/v4-migration-guide))。
### `sveltekit-2`
SvelteKit 1アプリをSvelteKit 2にアップグレードします([マイグレーションガイドを参照](../kit/migrating-to-sveltekit-2))。
### `package`
`@sveltejs/package`バージョン1を使用しているライブラリをバージョン2にアップグレードします。詳細は[プルリクエスト](https://github.com/sveltejs/kit/pull/8922)を参照してください。
### `routes`
プレリリースのSvelteKitアプリをSvelteKit 1のファイルシステムルーティング規則を使用するようにアップグレードします。詳細は[プルリクエスト](https://github.com/sveltejs/kit/discussions/5774)を参照してください。
# better-auth
[Better Auth](https://www.better-auth.com/) is a framework-agnostic authentication library for TypeScript.
## Usage
```sh
npx sv add better-auth
```
## What you get
- a complete auth setup for SvelteKit with Drizzle as the database adapter
- email/password authentication enabled by default
- optional demo registration and login pages
## Options
### demo
Which demo pages to include. Available values: `password` (Email & Password), `github` (GitHub OAuth).
```sh
# Email & Password only (default)
npx sv add better-auth="demo:password"
# GitHub OAuth only
npx sv add better-auth="demo:github"
# Both Email & Password and GitHub OAuth
npx sv add better-auth="demo:password,github"
```
# drizzle
[Drizzle ORM](https://orm.drizzle.team/) is a TypeScript ORM offering both relational and SQL-like query APIs, and which is serverless-ready by design.
## Usage
```sh
npx sv add drizzle
```
## What you get
- a setup that keeps your database access in SvelteKit's server files
- an `.env` file to store your credentials
- compatibility with the Better Auth add-on
- an optional Docker configuration to help with running a local database
## Options
### database
Which database variant to use:
- `postgresql` — the most popular open source database
- `mysql` — another popular open source database
- `sqlite` — file-based database not requiring a database server
```sh
npx sv add drizzle="database:postgresql"
```
### client
The SQL client to use, depends on `database`:
- For `postgresql`: `postgres.js`, `neon`,
- For `mysql`: `mysql2`, `planetscale`
- For `sqlite`: `better-sqlite3`, `libsql`, `turso`
```sh
npx sv add drizzle="database:postgresql+client:postgres.js"
```
Drizzle is compatible with well over a dozen database drivers. We just offer a few of the most common ones here for simplicity, but if you'd like to use another one you can choose one as a placeholder and swap it out for another after setup by choosing from [Drizzle's full list of compatible drivers](https://orm.drizzle.team/docs/connect-overview#next-steps).
### docker
Whether to add Docker Compose configuration. Only available for [`database`](#Options-database) `postgresql` or `mysql`
```sh
npx sv add drizzle="database:postgresql+client:postgres.js+docker:yes"
```
# eslint
[ESLint](https://eslint.org/) finds and fixes problems in your code.
## Usage
```sh
npx sv add eslint
```
## What you get
- the relevant packages installed including `eslint-plugin-svelte`
- an `eslint.config.js` file
- updated `.vscode/extensions.json`
- configured to work with TypeScript and `prettier` if you're using those packages
# mcp
[Svelte MCP](/docs/ai/overview) can help your LLM write better Svelte code.
## Usage
```sh
npx sv add mcp
```
## What you get
- An MCP configuration for [local](https://svelte.dev/docs/ai/local-setup) or [remote](https://svelte.dev/docs/ai/remote-setup) setup
- A [README for agents](https://agents.md/) to help you use the MCP server effectively
## Options
### ide
The IDE you want to use like `'claude-code'`, `'cursor'`, `'gemini'`, `'opencode'`, `'vscode'`, `'other'`.
```sh
npx sv add mcp="ide:cursor,vscode"
```
### setup
The setup you want to use.
```sh
npx sv add mcp="setup:local"
```
# mdsvex
[mdsvex](https://mdsvex.pngwn.io) is a markdown preprocessor for Svelte components - basically MDX for Svelte. It allows you to use Svelte components in your markdown, or markdown in your Svelte components.
## Usage
```sh
npx sv add mdsvex
```
## What you get
- mdsvex installed and configured in your `svelte.config.js`
# paraglide
[Paraglide from Inlang](https://inlang.com/m/gerre34r/library-inlang-paraglideJs) is a compiler-based i18n library that emits tree-shakable message functions with small bundle sizes, no async waterfalls, full type-safety, and more.
## Usage
```sh
npx sv add paraglide
```
## What you get
- Inlang project settings
- paraglide Vite plugin
- SvelteKit `reroute` and `handle` hooks
- `text-direction` and `lang` attributes in `app.html`
- updated `.gitignore`
- an optional demo page showing how to use paraglide
## Options
### languageTags
The languages you'd like to support specified as IETF BCP 47 language tags.
```sh
npx sv add paraglide="languageTags:en,es"
```
### demo
Whether to generate an optional demo page showing how to use paraglide.
```sh
npx sv add paraglide="demo:yes"
```
# playwright
[Playwright](https://playwright.dev) browser testing.
## Usage
```sh
npx sv add playwright
```
## What you get
- scripts added in your `package.json`
- a Playwright config file
- an updated `.gitignore`
- a demo test
# prettier
[Prettier](https://prettier.io) is an opinionated code formatter.
## Usage
```sh
npx sv add prettier
```
## What you get
- scripts in your `package.json`
- `.prettierignore` and `.prettierrc` files
- updates to your eslint config if you're using that package
# storybook
[Storybook](https://storybook.js.org/) is a frontend component workshop.
## Usage
```sh
npx sv add storybook
```
## What you get
- `npx storybook init` run for you from the same convenient `sv` CLI used for all other add-ons
- [Storybook for SvelteKit](https://storybook.js.org/docs/get-started/frameworks/sveltekit) or [Storybook for Svelte & Vite](https://storybook.js.org/docs/get-started/frameworks/svelte-vite) with default config provided, easy mocking of many SvelteKit modules, automatic link handling, and more.
# sveltekit-adapter
[SvelteKit adapters](/docs/kit/adapters) allow you to deploy your site to numerous platforms. This add-on allows you to configure officially provided SvelteKit adapters, but a number of [community-provided adapters](https://www.sveltesociety.dev/packages?category=sveltekit-adapters) are also available.
## Usage
```sh
npx sv add sveltekit-adapter
```
## What you get
- the chosen SvelteKit adapter installed and configured in your `svelte.config.js`
## Options
### adapter
Which SvelteKit adapter to use:
- `auto` — [`@sveltejs/adapter-auto`](/docs/kit/adapter-auto) automatically chooses the proper adapter to use, but is less configurable
- `node` — [`@sveltejs/adapter-node`](/docs/kit/adapter-node) generates a standalone Node server
- `static` — [`@sveltejs/adapter-static`](/docs/kit/adapter-static) allows you to use SvelteKit as a static site generator (SSG)
- `vercel` — [`@sveltejs/adapter-vercel`](/docs/kit/adapter-vercel) allows you to deploy to Vercel
- `cloudflare` — [`@sveltejs/adapter-cloudflare`](/docs/kit/adapter-cloudflare) allows you to deploy to Cloudflare
- `netlify` — [`@sveltejs/adapter-netlify`](/docs/kit/adapter-netlify) allows you to deploy to Netlify
```sh
npx sv add sveltekit-adapter="adapter:node"
```
### cloudflare target
Whether to deploy to Cloudflare Workers or Pages. Only available for `cloudflare` adapter.
```sh
npx sv add sveltekit-adapter="adapter:cloudflare+cfTarget:workers"
```
# tailwindcss
[Tailwind CSS](https://tailwindcss.com/) allows you to rapidly build modern websites without ever leaving your HTML.
## Usage
```sh
npx sv add tailwindcss
```
## What you get
- Tailwind setup following the [Tailwind for SvelteKit guide](https://tailwindcss.com/docs/installation/framework-guides/sveltekit)
- Tailwind Vite plugin
- updated `layout.css` and `+layout.svelte` (for SvelteKit) or `app.css` and `App.svelte` (for non-SvelteKit Vite apps)
- integration with `prettier` if using that package
## Options
### plugins
Which plugin to use:
- `typography` — [`@tailwindcss/typography`](https://github.com/tailwindlabs/tailwindcss-typography)
- `forms` — [`@tailwindcss/forms`](https://github.com/tailwindlabs/tailwindcss-forms)
```sh
npx sv add tailwindcss="plugins:typography"
```
# vitest
[Vitest](https://vitest.dev/) is a Vite-native testing framework.
## Usage
```sh
npx sv add vitest
```
## What you get
- the relevant packages installed and scripts added to your `package.json`
- client/server-aware testing setup for Svelte in your Vite config file
- demo tests
## Options
### usages
Which test types to use:
- `unit` — unit testing
- `component` — component testing
```sh
npx sv add vitest="usages:unit,component"
```
# [create your own]
> [!NOTE]
> Community add-ons are currently **experimental**. The API may change. Don't use them in production yet!
This guide covers how to create, test, and publish community add-ons for `sv`.
## Quick start
The easiest way to create an add-on is by using the `addon` template:
```sh
npx sv create --template addon [path]
```
The newly created project will have a `README.md` and `CONTRIBUTING.md` to guide you along.
## Project structure
Typically, an add-on looks like this:
```js
import { transforms } from '@sveltejs/sv-utils';
import { defineAddon, defineAddonOptions } from 'sv';
export default defineAddon({
id: 'addon-name',
shortDescription: 'a better description of what your addon does ;)',
options: defineAddonOptions()
.add('who', {
question: 'To whom should the addon say hello?',
type: 'string' // boolean | number | select | multiselect
})
.build(),
setup: ({ dependsOn, isKit, unsupported }) => {
if (!isKit) unsupported('Requires SvelteKit');
dependsOn('vitest');
},
run: ({ isKit, cancel, sv, options, file, language, directory }) => {
// Add "Hello [who]!" to the root page
sv.file(
directory.kitRoutes + '/+page.svelte',
transforms.svelte(({ ast, svelte }) => {
svelte.addFragment(ast, `Hello ${options.who}!
`);
})
);
},
nextSteps: ({ options }) => ['enjoy the add-on!']
});
```
The Svelte CLI is split into two packages with a clear boundary:
- [**`sv`**](sv) = **where and when** to do it. It owns paths, workspace detection, dependency tracking, and file I/O. The engine orchestrates add-on execution.
- [**`@sveltejs/sv-utils`**](sv-utils) = **what** to do to content. It provides parsers, language tooling, and typed transforms. Everything here is pure - no file system, no workspace awareness.
This separation means transforms are testable without a workspace and composable across add-ons.
## Development
You can run your add-on locally using the `file:` protocol:
```sh
cd /path/to/test-project
npx sv add file:../path/to/my-addon
```
This allows you to iterate quickly without publishing to npm.
The `file:` protocol also works for custom or private add-ons that you don't intend to publish - for example, to standardize project setup across your team or organization.
> [!NOTE]
> The `demo-add` script automatically builds your add-on before running it.
## Testing
The `sv/testing` module provides utilities for testing your add-on. `createSetupTest` is a factory that takes your vitest imports and returns a `setupTest` function. It creates real SvelteKit projects from templates, runs your add-on, and gives you access to the resulting files.
```js
import { expect } from '@playwright/test';
import fs from 'node:fs';
import path from 'node:path';
import { createSetupTest } from 'sv/testing';
import * as vitest from 'vitest';
import addon from './index.js';
const { test, testCases } = createSetupTest(vitest)(
{ addon },
{
kinds: [
{
type: 'default',
options: {
'your-addon-name': { who: 'World' }
}
}
],
filter: (testCase) => testCase.variant.includes('kit'),
browser: false
}
);
test.concurrent.for(testCases)('my-addon $kind.type $variant', async (testCase, ctx) => {
const cwd = ctx.cwd(testCase);
const page = fs.readFileSync(path.resolve(cwd, 'src/routes/+page.svelte'), 'utf8');
expect(page).toContain('Hello World!');
});
```
Your `vitest.config.js` must include the global setup from `sv/testing`:
```js
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['tests/**/*.test.{js,ts}'],
globalSetup: ['tests/setup/global.js']
}
});
```
And the global test setup script `tests/setup/global.js`:
```js
import { fileURLToPath } from 'node:url';
import { setupGlobal } from 'sv/testing';
const TEST_DIR = fileURLToPath(new URL('../../.test-output/', import.meta.url));
export default setupGlobal({ TEST_DIR });
```
## Publishing
### Bundling
Community add-ons are bundled with [tsdown](https://tsdown.dev/) into a single file. Everything is bundled except `sv`. (It is a peer dependency provided at runtime.)
### `package.json`
Your add-on must have `sv` as a peer dependency and **no** `dependencies` in `package.json`:
```jsonc
{
"name": "@my-org/sv",
"version": "1.0.0",
"type": "module",
// bundled entrypoint (tsdown outputs .mjs for ESM)
"exports": {
".": { "default": "./dist/index.mjs" }
},
"publishConfig": {
"access": "public"
},
// cannot have dependencies
"dependencies": {},
"peerDependencies": {
// minimum version required to run by this add-on
"sv": "^0.13.0"
},
// Add the "sv-add" keyword so users can discover your add-on
"keywords": ["sv-add", "svelte", "sveltekit"]
}
```
### Naming convention
#### packages names
If you name your package `@my-org/sv`, users can install it by typing just the org handle:
```sh
npx sv add @my-org
```
It's also possible to publish like `@my-org/core`, just users will need to type the full package name.
```sh
npx sv add @my-org/core
```
Users can also ask for a specific version:
```sh
npx sv add @my-org/sv@1.2.3
```
When no version is specified, `latest` is used.
> [!NOTE]
> Unscoped packages are not supported yet
#### export options
`sv` first tries to import `your-package/sv`, then falls back to the default export. This means you have two options:
1. **Default export** (for dedicated add-on packages):
```json
{
"exports": {
".": "./src/index.js"
}
}
```
2. **`./sv` export** (for packages that also export other functionality):
```json
{
"exports": {
".": "./src/main.js",
"./sv": "./src/addon.js"
}
}
```
### Publish to npm
```sh
npm login
npm publish
```
> `prepublishOnly` automatically runs the build before publishing.
## Next steps
You can optionally display guidance in the console after your add-on runs:
```js
import { color } from '@sveltejs/sv-utils';
export default defineAddon({
// ...
nextSteps: ({ options }) => [
`Run ${color.command('npm run dev')} to start developing`,
`Check out the docs at https://...`
]
});
```
## Version compatibility
Your add-on should specify a minimum `sv` version in `peerDependencies`. Your users will get a compatibility warning if their `sv` version has a different major version than what was specified.
## Examples
See the [official add-on source code](https://github.com/sveltejs/cli/tree/main/packages/sv/src/addons) for some real world examples.
# sv
`sv` exposes a programmatic API for creating projects and running add-ons.
## `defineAddon`
Creates an add-on definition. See [create your own](community) for a full guide.
```js
import { transforms } from '@sveltejs/sv-utils';
import { defineAddon, defineAddonOptions } from 'sv';
export default defineAddon({
id: 'my-addon',
options: defineAddonOptions().build(),
// called before run — declare dependencies and environment requirements
setup: ({ dependsOn, unsupported, isKit }) => {
if (!isKit) unsupported('Requires SvelteKit');
dependsOn('eslint');
},
// the actual work — add files, edit files, declare dependencies
run: ({ sv, options, cancel }) => {
// add a dependency
sv.devDependency('my-lib', '^1.0.0');
// create or edit files using transforms from @sveltejs/sv-utils
sv.file('src/lib/foo.ts', (content) => {
return 'export const foo = true;';
});
sv.file(
'src/routes/+page.svelte',
transforms.svelte(({ ast, svelte }) => {
svelte.addFragment(ast, 'Hello!
');
})
);
// cancel at any point if something is wrong
// cancel('reason');
},
// displayed after the add-on runs
nextSteps: ({ options }) => ['Run `npm run dev` to get started']
});
```
The `sv` object in `run` provides `file`, `dependency`, `devDependency`, and `execute`. For file transforms (AST-based editing of scripts, Svelte components, CSS, JSON, etc.) and package manager helpers, see [`@sveltejs/sv-utils`](sv-utils).
## `defineAddonOptions`
Builder for add-on options. Chained with `.add()` and finalized with `.build()`.
```js
import { defineAddonOptions } from 'sv';
const options = defineAddonOptions()
.add('database', {
question: 'Which database?',
type: 'select',
default: 'postgresql',
options: [
{ value: 'postgresql' },
{ value: 'mysql' },
{ value: 'sqlite' }
]
})
.add('docker', {
question: 'Add a docker-compose file?',
type: 'boolean',
default: false,
// only ask when database is not sqlite
condition: (opts) => opts.database !== 'sqlite'
})
.build();
```
Options are asked in order. The `condition` callback receives the answers collected so far — return `false` to skip the question (its value will be `undefined`).
## `create`
Programmatically create a new Svelte project.
```js
import { create } from 'sv';
create('./my-app', {
name: 'my-app',
template: 'minimal',
types: 'typescript'
});
```
## `add`
Programmatically run add-ons against an existing project.
```js
import { add, officialAddons } from 'sv';
await add({
cwd: './my-app',
addons: { prettier: officialAddons.prettier },
options: { prettier: {} },
packageManager: 'npm'
});
```
# sv-utils
> [!NOTE]
> `@sveltejs/sv-utils` is currently **experimental**. The API may change.
`@sveltejs/sv-utils` is an add-on utilty for parsing, transforming, and generating code..
```sh
npm install -D @sveltejs/sv-utils
```
## transforms
`transforms` is a collection of parser-aware functions that lets you modify the files via abstract syntax tree (AST). It accepts a callback function. The return value is designed to be be passed directly into `sv.file()`. The parser choice is baked into the transform type - you can't accidentally parse a vite config as Svelte because you never call a parser yourself.
Each transform injects relevant utilities into the callback, so you only need one import:
```js
import { transforms } from '@sveltejs/sv-utils';
transforms.script(/* ... */);
transforms.svelte(/* ... */);
// ...
```
### `transforms.script`
Transform a JavaScript/TypeScript file. The callback receives `{ ast, comments, content, js }`.
```js
// @noErrors
import { transforms } from '@sveltejs/sv-utils';
sv.file(
file.viteConfig,
transforms.script(({ ast, js }) => {
js.imports.addDefault(ast, { as: 'foo', from: 'foo' });
js.vite.addPlugin(ast, { code: 'foo()' });
})
);
```
### `transforms.svelte`
Transform a Svelte component. The callback receives `{ ast, content, svelte, js }`.
```js
// @noErrors
import { transforms } from '@sveltejs/sv-utils';
sv.file(
layoutPath,
transforms.svelte(({ ast, svelte }) => {
svelte.addFragment(ast, ' ');
})
);
```
### `transforms.svelteScript`
Transform a Svelte component with a `