This is the developer documentation for Svelte CLI.
# Overview
The command line interface (CLI), `sv`, is a toolkit for creating and maintaining Svelte applications.
## Usage
```sh
npx sv
```
## Commands
- [`sv create`](sv-create) — scaffold a new Sveltekit project, with the option to set up add-ons in one go
- [`sv add`](sv-add) — apply add-ons to an existing project
- [`sv migrate`](sv-migrate) — migrate your Svelte(Kit) codebase between versions
- [`sv check`](sv-check) — analyze your code with [svelte-check](https://github.com/sveltejs/language-tools)
Run `sv --help` to see all options for a command.
## Add-ons
An add-on is a pre-packaged integration that applies itself to your project: it installs dependencies, writes config files, and may ask follow-up questions (like which database to use).
There are two types:
- **Official add-ons** are developed and maintained in the [Svelte CLI repository](https://github.com/sveltejs/cli) by the Svelte team, and have been vetted for both quality and safety. They're a deliberately small set of widely used, best-in-class integrations. See the [full list of official add-ons](sv-add#Official-add-ons).
- **Community add-ons** are npm packages published by the community, letting any library or tool become a one-liner install with `npx sv add my-addon`. Svelte maintainers have not reviewed them for malicious code — see the [community add-ons docs](sv-add#Community-add-ons) for how to find and install them.
Want to make your own add-on? Follow the [create your own guide](community).
## Acknowledgements
Thank you to [Christopher Brown](https://github.com/chbrown) who originally owned the `sv` name on npm for graciously allowing it to be used for the Svelte CLI. You can find the original `sv` package at [`@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)
## Why are there two packages, `sv` and `@sveltejs/sv-utils`?
They have a clear boundary:
- [`sv`](sv) decides **where and when**: paths, workspace detection, dependencies and file I/O.
- [`@sveltejs/sv-utils`](sv-utils) decides **what** to do to content: parsers and pure transforms, with no file system or workspace awareness.
This keeps transforms testable without a workspace and composable across add-ons.
## Should my add-on bundle `@sveltejs/sv-utils`?
Most breaking changes land in `@sveltejs/sv-utils`, not `sv`. Each `sv` release ships one exact `@sveltejs/sv-utils` version, so you have two options:
- **Bundled** (template default): pins the version you tested against. Safest, costs ~1 MB.
- **Unbundled**: declare it in `peerDependencies`. Your add-on stays tiny and runs against the copy `sv` ships. When majors differ, `sv` warns and prints the command to rerun with the `sv` you built for: `npx sv@ add `.
If an unbundled add-on breaks for your users, they can run that command, and you can publish a fix for the latest `sv`. See [bundling](community#Publishing-Bundling).
# sv create
`sv create` sets up a new SvelteKit project, with options to [setup additional functionality](sv-add#Official-add-ons).
## Usage
```sh
npx sv create [options] [path]
```
## Options
### `--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 `
Which project template to use:
- `minimal` — barebones scaffolding for your new app
- `demo` — showcase app with a word guessing game that works without JavaScript
- `library` — template for a Svelte library, set up with `svelte-package`
- `addon` — template for a community add-on, ready to be tested & published
### `--types `
Whether and how to add typechecking to the project:
- `ts` — default to `.ts` files and use `lang="ts"` for `.svelte` components
- `jsdoc` — use [JSDoc syntax](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html) for types
### `--no-types`
Prevent typechecking from being added. Not recommended!
### `--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`
Run the command without the interactive add-ons prompt
### `--no-download-check`
Do not warn about downloads from community add-ons.
> [!NOTE]
> Svelte maintainers have not reviewed community add-ons for malicious code! Use at your discretion.
### `--addon-name `
Specify the package name when creating an addon template. Accepts `@/` or ``. When omitted, you will be prompted for the name.
### `--install `
Installs dependencies with a specified package manager:
- `npm`
- `pnpm`
- `yarn`
- `bun`
- `deno`
### `--no-install`
Prevents installing dependencies.
### `--no-dir-check`
Skip checking whether the target directory is empty.
# sv add
`sv add` updates an existing project with new functionality.
## Usage
```sh
npx sv add
```
```sh
npx sv add [add-ons]
```
You can select multiple space-separated add-ons from [the list below](#Official-add-ons), or you can use the interactive prompt.
## Options
### `-C`, `--cwd`
Path to the root of your Svelte(Kit) project.
### `--no-git-check`
Do not warn about uncommitted changes.
### `--no-download-check`
Do not warn about downloads from community add-ons.
> [!NOTE]
> 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`
Do not prompt to install dependencies.
## Official add-ons
Official add-ons are developed and maintained in the [Svelte CLI repository](https://github.com/sveltejs/cli) by the Svelte team, and have been vetted for both quality and safety. The set is intentionally small — it covers widely used, best-in-class integrations, while everything else is published as a [community add-on](#Community-add-ons). Each add-on's page describes what it sets up and the options available for it.
- [`ai-tools`](ai-tools)
- [`better-auth`](better-auth)
- [`drizzle`](drizzle)
- [`enhanced-img`](enhanced-img)
- [`eslint`](eslint)
- [`mdsvex`](mdsvex)
- [`paraglide`](paraglide)
- [`playwright`](playwright)
- [`prettier`](prettier)
- [`storybook`](storybook)
- [`sveltekit-adapter`](sveltekit-adapter)
- [`tailwindcss`](tailwind)
- [`vitest`](vitest)
## Community add-ons
> [!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. 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 addon-on
npx sv add my-addon
# Also works with org names
npx sv add @supacool/sv
# As a shorthand, packages named `sv` can be omitted
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` runs [`svelte-check`](https://npmx.dev/package/svelte-check) in your project and reports errors and warnings such as unused CSS, accessibility hints, and JavaScript/TypeScript compiler errors.
It runs `svelte-check` internally, and only if it is installed in your project (global installs are ignored):
```sh
npm i -D svelte-check
npx sv check
```
## Options
All [`svelte-check` options](https://npmx.dev/package/svelte-check) are forwarded, plus:
### `-C`, `--cwd `
Path to the root of your project. Defaults to the current working directory.
# sv migrate
`sv migrate` migrates Svelte and SvelteKit codebases. Newer migrations use the task-based migration system in `sv`. Legacy migrations are delegated to [`svelte-migrate@1`](https://www.npmjs.com/package/svelte-migrate) and are kept available for older projects, but no longer receive updates.
Before migrating, make sure the project is committed and read the migration's linked changelog or migration guide. Migration code cannot account for every application, so review the resulting diff and run your project's checks after every step.
## Usage
```sh
npx sv migrate
```
When no migration is specified, `sv migrate` prompts you to pick one.
You can also specify a migration directly via the CLI:
```sh
npx sv migrate [migration]
```
For task-based migrations, `sv migrate` shows the migration tasks before applying them. Prerequisite tasks always run, and the remaining tasks can be selected interactively or with `--tasks`.
To make migration changes easier to review, run one selectable task at a time and commit the result before starting the next one. The task system is intended to create focused commits, not independent migration paths. Do not expect a project to work after running only a few tasks. Most projects need all applicable tasks before the migration is complete.
After a successful task-based migration, `sv` formats the changes using the project's `format` or `fmt` script when one exists, otherwise it formats changed files with Prettier when available. It then prompts to install updated dependencies. Some transformations leave `@migration-task` comments where manual work is required; search the project for that exact marker before considering the migration complete.
## Task-based migrations
### `sveltekit-3`
Upgrades a SvelteKit 2 app to SvelteKit 3. Read the [SvelteKit 3 changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md#300) before running it.
The migration is divided into these tasks:
- `package-json` (prerequisite) updates package versions for SvelteKit 3.
- `tsconfig` (prerequisite) extends the generated `$app/tsconfig` instead of `.svelte-kit/tsconfig.json`.
- `svelte-config` moves supported configuration from `svelte.config.*` into `vite.config.*` and updates imports of the old config where possible.
- `environment` replaces legacy environment modules with `$app/env` and creates `src/env.js` or `src/env.ts` declarations when needed.
- `paths` migrates deprecated `$app/paths` APIs and path types.
- `external-redirects` opts external redirects into the new redirect behavior.
- `shallow-routing` replaces shallow-routing APIs with `goto` calls.
- `params` consolidates route parameter matchers into `src/params.js` or `src/params.ts`.
- `app-state` migrates `$app/stores` usage to `$app/state`.
The migration only changes patterns it can identify safely. Review `@migration-task` comments and the SvelteKit 3 changelog for changes that require manual work.
### `app-state`
Migrates `$app/stores` usage to `$app/state` in `.svelte` files. See the [migration guide](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated) for more details.
## Legacy migrations
The migrations below run through `svelte-migrate@1`. They remain available so older projects can move forward, but they no longer receive fixes or support for newly discovered code patterns. Commit your project first and carefully review their output.
### `svelte-5`
Upgrades a Svelte 4 app to use Svelte 5, and updates individual components to use [runes](../svelte/what-are-runes) and other Svelte 5 syntax ([see migration guide](../svelte/v5-migration-guide)).
### `self-closing-tags`
Replaces all the self-closing non-void elements in your `.svelte` files. See the [pull request](https://github.com/sveltejs/kit/pull/12128) for more details.
### `svelte-4`
Upgrades a Svelte 3 app to use Svelte 4 ([see migration guide](../svelte/v4-migration-guide)).
### `sveltekit-2`
Upgrades a SvelteKit 1 app to SvelteKit 2 ([see migration guide](../kit/migrating-to-sveltekit-2)).
### `package`
Upgrades a library using `@sveltejs/package` version 1 to version 2. See the [pull request](https://github.com/sveltejs/kit/pull/8922) for more details.
### `routes`
Upgrades a pre-release SvelteKit app to use the filesystem routing conventions in SvelteKit 1. See the [pull request](https://github.com/sveltejs/kit/discussions/5774) for more details.
## Options
These options apply to both task-based and legacy migrations.
### `--cwd `
Run the migration in a different working directory. The path defaults to the current directory and must contain a `package.json`.
### `--no-git-check`
By default, `sv migrate` prompts before making changes when the git working tree is dirty. Use `--no-git-check` to skip this check.
### `--confirm`
Skip the final confirmation prompt before applying the migration. This does not skip migration selection or the dirty-working-tree check; provide the migration name and corresponding options for non-interactive use.
## Task-based migration options
These options do not apply to legacy migrations. Legacy migrations do not support task or file selection, and manage their own dependency installation behavior.
### `--files `
Limit the files saved by the migration to those matching a glob. This is an advanced escape hatch, not a way to run a complete migration on part of a project. Tasks often make related changes across configuration, source, and generated files; excluding any of them can leave imports, configuration, or types inconsistent and the project temporarily broken.
A task may still attempt to edit or create a file outside the glob. `sv migrate` does not save that file and reports it under **Unmodified files**. Review that list and rerun the relevant task without the filter, with a broader filter, or make the omitted changes manually.
When used with `--cwd`, the glob is relative to the working directory.
### `--tasks [task...]`
Select migration tasks without the interactive task prompt. Prerequisite tasks always run because they lay the foundation for the remaining tasks.
Use `--tasks` without any task IDs to print all available tasks for the migration without running them.
Use `--tasks all` to run every task, or `--tasks prerequisite` to run only the prerequisite tasks.
To keep changes reviewable, pass one task ID at a time, review and commit the result, then run the next task. Use `--tasks all` primarily for automation or when a single combined diff is intentional.
### `--install `
Install dependencies with a specified package manager:
- `npm`
- `pnpm`
- `yarn`
- `bun`
- `deno`
### `--no-install`
Skip installing dependencies after the migration.
# ai-tools
The [Svelte AI tools](/docs/ai/overview) can help your LLM write better Svelte code.
## Usage
```sh
npx sv add ai-tools
```
## What you get
You can add the tooling either through the official Svelte plugin or as individual tools.
- The Svelte plugin bundles everything (MCP server, [skills](https://svelte.dev/docs/ai/skills) and sub-agents) and keeps itself up to date. It's available for Claude Code, OpenCode and Pi. For Claude Code it's enabled through a committed `.claude/settings.json` - the first time you open the project you'll be asked to trust the workspace, then it installs automatically (no `/plugin install` needed).
- Individual tools, for clients without a plugin (or when you want to pick exactly what to add):
- 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
- [Skills](https://svelte.dev/docs/ai/skills) for clients that support them
- Sub-agents for clients that support them
## Options
### ide
The client(s) you want to use like `'claude-code'`, `'cursor'`, `'gemini'`, `'opencode'`, `'pi'`, `'vscode'`, `'other'`.
```sh
npx sv add ai-tools="ide:cursor,vscode"
```
### delivery
How to add the tooling: `'plugin'` (the Svelte plugin, recommended) or `'tools'` (individual tools). Only asked when a selected client supports a plugin.
```sh
npx sv add ai-tools="ide:claude-code+delivery:plugin"
```
### tools
Which individual tools to add when not using the plugin, like `'mcp'`, `'svelte-code-writer'`, `'svelte-core-bestpractices'`, `'svelte-file-editor'`.
```sh
npx sv add ai-tools="ide:cursor+delivery:tools+tools:mcp,svelte-file-editor"
```
### mcpSetup
The MCP setup you want to use (`'local'` or `'remote'`). Only relevant when adding the MCP server as an individual tool.
```sh
npx sv add ai-tools="mcpSetup:local"
```
### agentsMd
Whether to add a [README for agents](https://agents.md/) (`AGENTS.md`, or `GEMINI.md` for Gemini, plus a `.claude/CLAUDE.md` pointing to `AGENTS.md` for Claude Code). Defaults to `true`. Not asked when no selected client would get one: the Svelte plugin (Claude Code with `delivery:plugin`, OpenCode and Pi) already covers it.
```sh
npx sv add ai-tools="ide:cursor+agentsMd:no"
```
### optInSkills
Which opt-in [skills](https://svelte.dev/docs/ai/skills) to add, like `'svelte-mcp-feedback'` (reports Svelte mistakes you correct to the [ai-tools](https://github.com/sveltejs/ai-tools) repo so the MCP autofixer can catch them). None are added by default. Opt-in skills aren't bundled with the Svelte plugin, so this is asked for every client that supports skills, even when you choose the plugin. The question is skipped when every selected client can already load the opt-in skills from one of its skills folders (for example Cursor also loads `.claude/skills`, and Pi also loads `.agents/skills`). Skills are only written for the clients that can't load them yet, so `sv` doesn't add a second copy for a client that already sees one.
```sh
npx sv add ai-tools="ide:claude-code+delivery:plugin+optInSkills:svelte-mcp-feedback"
```
# 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"
```
# enhanced-img
[`@sveltejs/enhanced-img`](https://svelte.dev/docs/kit/images) serves smaller file formats like `avif` or `webp`, generates the right sizes for different devices, and sets `width` and `height` to avoid layout shift.
## Usage
```sh
npx sv add enhanced-img
```
## What you get
- the `enhancedImages` Vite plugin
- rewrite applicable ` ` tags to ``
- `sharp` added to the allowed builds when using pnpm
# 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
# experimental
Enables experimental Svelte and [SvelteKit](https://svelte.dev/docs/kit/configuration#experimental) features.
## Usage
```sh
npx sv add experimental
```
## What you get
- the selected experimental flags set in your config
## Options
### features
Which experimental flags to enable:
- `async` — `await` in components
- `remoteFunctions` — remote functions
- `forkPreloads` — forked preloading
```sh
npx sv add experimental="features:async,remoteFunctions"
```
# 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`
- an example e2e test
- an optional demo page the e2e test runs against
## Options
### demo
Whether to generate a demo page at `/demo/playwright` (listed in the `DemoLinks` post-it) for the example e2e test. Without it, the test targets `/`.
```sh
npx sv add playwright="demo:yes"
```
# 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]
This guide covers how to create, test, and publish community add-ons for the Svelte CLI.
## 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, runsAfter, isKit, unsupported, addOption }) => {
if (!isKit) unsupported('Requires SvelteKit');
dependsOn('vitest'); // required add-on
runsAfter('prettier'); // ordering only
// dynamically add options (e.g. based on workspace state or fetched data)
// addOption('key', { question: '...', type: 'boolean', default: true });
},
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 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.
[Why are there two packages.](faq#Why-are-there-two-packages-sv-and-sveltejs-sv-utils)
## 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 fs from 'node:fs';
import path from 'node:path';
import { expect } from '@playwright/test';
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 path from 'node:path';
import { setupGlobal } from 'sv/testing';
// test projects are scaffolded into `/.test-output`
const TEST_DIR = path.resolve(import.meta.dirname, '..', '..', '.test-output');
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.)
[`@sveltejs/sv-utils`](sv-utils) is bundled as well to pin its version. To keep your add-on small, you can leave it unbundled by moving it to `peerDependencies` (tsdown never bundles peers):
```jsonc
"peerDependencies": {
"sv": "^1.4.0",
// resolved from the copy `sv` ships, `sv` warns on a major mismatch
"@sveltejs/sv-utils": "^1.1.0"
}
```
Keep `sv` at the version you tested with: on mismatch, users are told to run `npx sv@1.4.0 add `. See [the trade-off](faq#Should-my-add-on-bundle-sveltejs-sv-utils).
### `package.json`
Your add-on must have `sv` as a peer dependency. Any `dependencies` declared will **not** be available at runtime, everything must be bundled:
```jsonc
{
"name": "@my-org/sv",
"version": "1.0.0",
"type": "module",
// bundled entry point (tsdown outputs .mjs for ESM)
"exports": {
".": { "default": "./dist/index.mjs" }
},
"publishConfig": {
"access": "public"
},
// packages declared here will not be available during runtime, it must be bundled
"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 with https://www.npmx.dev/search?q=keyword:sv-add
"keywords": ["sv-add", "svelte", "sveltekit"]
}
```
### Package names
Naming follows the same [restrictions](https://npmx.dev/package/validate-npm-package-name#user-content-naming-rules) as on npm:
```sh
npx sv add my-addon
npx sv add @my-org/sv
npx sv add @my-org/foo
```
An add-on published as `@/sv` can also be installed as `@`. The following all resolve to the same package:
```sh
npx sv add @my-org
npx sv add @my-org/sv
npx sv add @my-org/sv@latest
```
For a specific version, append `@`:
```sh
npx sv add @my-org/sv@1.2.3
npx sv add my-addon@1.2.3
```
### Entry points
The CLI looks for `./sv` first. If that is not found, it defaults to the `.` entry point. This means you have two options:
1. **Default export** (for a dedicated add-on package):
```json
{
"name": "@my-org/sveltekit-addon",
"exports": {
".": "./dist/addon.mjs"
}
}
```
2. **`./sv` export** (for packages that also export other functionality):
```json
{
"name": "@my-org/sveltekit-addon",
"exports": {
".": "./dist/main.mjs",
"./sv": "./dist/addon.mjs"
}
}
```
### 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, environment requirements, and dynamic options
setup: ({ dependsOn, runsAfter, unsupported, addOption, isKit }) => {
if (!isKit) unsupported('Requires SvelteKit');
dependsOn('eslint');
runsAfter('prettier');
// dynamically add options based on workspace state or fetched data
addOption('theme', {
question: 'Which theme?',
type: 'select',
default: 'dark',
options: [{ value: 'dark' }, { value: 'light' }]
});
},
// 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;';
});
// remove a file (respects the migration file filter)
sv.removeFile('src/lib/obsolete.ts');
// edit multiple existing files
sv.files(
{
include: 'src/**/*.{js,ts,svelte}',
exclude: 'src/**/+layout.{js,ts,svelte}',
where: (content) => content.includes('old-value')
},
(content, path) => content.replaceAll('old-value', 'new-value')
);
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']
});
```
Official add-ons included in `dependsOn` will be installed automatically. Community add-ons must be included as part of the same command.
`dependsOn` also implies `runsAfter`. Use `runsAfter` alone when you only care about ordering.
`dependsOn` and `runsAfter` both accept official and community add-on ids. (`'sveltekit-adapter'`, `'better-auth'`, ...)
The `sv` object in `run` provides `file`, `files`, `removeFile`, `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).
### Typed dynamic options
If your add-on adds options dynamically in `setup` (e.g. from a fetch), you can pass a type parameter to `defineAddon` to get strong typing for those options:
```ts
import { defineAddon, defineAddonOptions } from 'sv';
// ---cut---
const addon = defineAddon<{ theme: string }>()({
id: 'my-addon',
options: defineAddonOptions().build(),
setup: ({ addOption }) => {
addOption('theme', {
question: 'Which theme?',
type: 'string',
default: 'dark'
});
},
run: ({ options }) => {
options.theme; // string
}
});
```
The type parameter maps value types (`boolean`, `string`, `number`) to question definitions. Without it, `defineAddon` stays strict and only allows statically defined options.
## `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`).
### Exporting your option types
Pass the values your options produce to `defineAddonOptions`. `build()` then checks your questions against them, both ways, and you get a small type to export for consumers of your add-on:
```ts
import { defineAddonOptions } from 'sv';
// ---cut---
export type MyAddonOptions = { database: 'postgresql' | 'sqlite'; docker: boolean };
const options = defineAddonOptions()
.add('database', {
question: 'Which database?',
type: 'select',
default: 'sqlite',
options: [{ value: 'postgresql' }, { value: 'sqlite' }]
})
.add('docker', { question: 'Add a docker-compose file?', type: 'boolean', default: false })
.build();
```
Official add-ons follow the same pattern. `OfficialAddonOptions` is what `add()` accepts for them, keyed by add-on id:
```ts
import type { OfficialAddonOptions } from 'sv';
// ---cut---
// unanswered questions fall back to their default
const drizzle: OfficialAddonOptions['drizzle'] = { database: 'sqlite', docker: false };
```
## `create`
Programmatically create a new Svelte project.
```js
import { create } from 'sv';
create({
cwd: './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
`@sveltejs/sv-utils` is an add-on utility for parsing, transforming, and generating code..
```sh
npm install -D @sveltejs/sv-utils
```
> [!NOTE]
> Bundle `@sveltejs/sv-utils` in your add-on to pin its version, or declare it in `peerDependencies` to use the copy `sv` ships. See [the trade-off](faq#Should-my-add-on-bundle-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 `