Svelte 2 🧡 Setting Up Projects with Vite and sv CLI Tooling
Svelte 2 replaced the traditional React/Vue render‑diff model with a pure compiler that turns .svelte markup into ordinary JavaScript. While the compiler existed before Vite, today’s workflow leans heavily on Vite’s lightning‑fast dev server and its native ESM handling. The companion sv command‑line tool wraps Svelte’s compile step, giving you instant hot‑module replacement, a single command to build or preview, and clear feedback on what changed. This chapter shows how to bootstrap a fresh Svelte 2 project, wire Vite and sv, add TypeScript, and get your first build and preview running in minutes. By the end you’ll see that a whole application lives in just a few files and that the entire stack can be started with one terminal session.
Key point: With Vite and sv, a Svelte 2 project becomes a handful of files—one .svelte source, one compiled .js output—and you can preview or build with sv build or sv watch without ever leaving the terminal.
Why schema-first validation exists
(Note: This section mirrors the “Why” pattern from earlier tutorials.)
The performance gap. A virtual DOM forces every update to compare an entire tree, even when only one leaf changed. Svelte removes that comparison entirely; the compiler knows exactly which DOM nodes a state change touches because those connections were written into the generated code during compilation. The browser therefore executes only the minimal DOM writes needed.
Instant feedback via Hot Module Replacement. Vite’s HMR watches .svelte files and re‑runs the compiler on the modified source, updating the live DOM without a full rebuild. Because Svelte already emits effect calls tied to signal reads, the update path is immediate and requires no reconciler pass.
First‑class ESM support. Modern browsers treat ESM natively; Vite ships with automatic module resolution, so .svelte files that export functions become regular ES modules without any configuration tricks. This eliminates the common “Cannot find module ‘svelte’” error that appears when mixing CJS and ESM.
One‑command builds and previews. Running sv build produces a production‑ready directory, while sv preview opens a local dev server that serves the freshly compiled chunks. Both commands are a single invocation away from getting artifacts ready for deployment.
Reduced mental overhead for newcomers. Svelte’s markup looks like HTML, but the compiler does the heavy lifting. New users who know plain JavaScript and HTML can focus on writing templates rather than managing a virtual tree or understanding diff algorithms.
a. Installing Node and Dependencies
Before you start, verify you have Node ≥ 18 and npm or yarn installed. Create a project folder and initialise it:
mkdir my-svelte-project && cd my-svelte-project
npm init -y
Pick a package manager. Here we use npm. Install the core pieces:
npm i svelte vite
# Optional, if you prefer Yarn:
# yarn add svelte vite
If you plan to use the official sv CLI, install it via npm:
npm i -D sv # assumes a package named `sv` publishes the CLI
Verify the CLI is available:
sv --version
You should see something like sv 1.0.0. If not, install from GitHub releases or add it as a dev dependency.
b. Creating the Project with Vite
Vite discovers Svelte files automatically once the vite-plugin-svelte plugin is loaded. First, create the basic layout:
mkdir -p src/components
touch src/App.svelte src/index.html
Edit src/App.svelte minimally:
<script>
let count = 0;
</script>
<button onclick={() => ++count}>
Count is {count}
</button>
<style>
button { font-size: 1rem; }
</style>
<main>
<h1>Hello Svelte</h1>
</main>
Now initialise Vite with the Svelte plugin:
npm pkg init -d vite
Replace the generated vite.config.ts with:
import { defineConfig } from 'vite';
import svelte from '@vitejs/plugin-svelte'; // ← plugin for Svelte 2/5
export default defineConfig({
plugins: [svelte()],
server: { importSource: './', publicDir: './static' },
});
Save and run:
npm run dev # starts Vite dev server
npm run build # runs `sv build`
The dev server will serve the compiled output immediately thanks to HMR.
c. TypeScript and ESM Setup
Enable TypeScript in package.json:
{
"name": "my-svelte-project",
"scripts": {
"dev": "vite",
"build": "sv build",
"preview": "sv preview"
},
"type": "module" // makes all imports ESM by default
}
Create a tsconfig.json at the root:
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020"],
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
}
Run tsc --noEmit to verify there are no type errors. The presence of "type": "module" ensures Vite treats .js files as ES modules, allowing imports from other packages without transpilation.
Complete Example Session
Below is a self‑contained component called Counter.svelte that demonstrates reactivity, derived values, and bindings. Save the following as src/Counter.svelte.
<!-- src/Counter.svelte -->
<script>
// A reactive source declared with a rune
let count = $state(0);
// A derived value computed lazily from another reactive source
let doubled = $derived(count * 2);
function increment() {
count += 1;
}
</script>
<button onclick={increment}>
Click → {count} doubled is {doubled}
</button>
<style>
button { padding: 0.5rem 1rem; cursor: pointer; }
</style>
Part 1 – Source file
The file contains only ordinary variables marked $state and $derived. No hooks, no JSX, no virtual DOM references.
Part 2 – Compile with sv build
npm run build # runs `sv build`
This command tells Vite to invoke the sv CLI, which internally runs svelte compile on src/Counter.svelte and writes the emitted JavaScript to dist/Counter.js. Open dist/Counter.js and look for the generated set_text and effect calls. They illustrate the compiler’s decision to update only the text node containing {count} and {doubled}.
Part 3 – Preview locally
npm run preview
The Vite dev server reloads the updated .js file and renders the button label dynamically. You see the number increase instantly, confirming hot module replacement.
Part 4 – Output inspection
cat dist/Counter.js
You’ll see something like:
import { template, set_text, listen, mutate } from "svelte/internal/client";
const tmpl = template("<button>Click → </button>"); // parsed once
export default function Counter($$anchor) {
let count = $.state(0);
let doubled = $.derived(count * 2);
function increment() {
$.set(count, $.get(count) + 1);
}
const button = tmpl();
const text = button.firstChild;
$.set_text(text, $.get(count)); // initial render
$.listen(button, "click", increment); // event binding
$.effect(() => {
$.set_text(text, $.get(doubled));
});
$.append($$anchor, button);
}
Notice there is no render() call, no virtual tree, and no diffing logic. The update is a direct assignment to a DOM node triggered by signal propagation.
Divider
Quick Reference
Core Tools
| Tool | Command | Purpose |
|---|---|---|
npm run dev | vite | Starts Vite dev server with HMR |
npm run build | sv build | Produces production bundle |
sv preview | sv preview | Serves compiled chunks for interactive preview |
sv watch | sv watch | Live preview while editing |
File Extensions
| Source | Emitted output | Notes |
|---|---|---|
.svelte | .js (or .mjs) | Plain JavaScript, no wrapper |
<script> block | Generated function | Exported as default or named export |
<style> block | Scoped CSS file | Hash‑based selectors injected at compile time |
Vite Plugin
import svelte from '@vitejs/plugin-svelte';
// Register it in vite.config.ts under `plugins: [svelte()]`
Best Practices
✅ Do This:
// Enable HMR in Vite dev server
npm run dev // auto-reload on .svelte changes
// Run `sv build` for production bundles
npm run build // creates ./dist/
// Keep TypeScript strict mode on
tsc --noEmit
❌ Don’t Do This:
// Manually compile with `svelte-build` instead of `sv build`
// Ignoring Vite's HMR leads to stale pages
// Mixing CJS and ESM without `"type": "module"`
// Adding `let` state expecting reactivity without `$state`
- Always declare reactive state with a rune (
$state). - Derive computed values with
$derived; never store them in$stateunless intentional. - Use
bind:for two-way inputs; do not rely onv-bindalone. - Scope styles with hash selectors; Vite injects them automatically.
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
sv build fails with “No such file” | Wrong importSource or missing vite.config.ts | Verify server.importSource points to the project root |
| Runtime errors about “Cannot find module ‘svelte’” | ESM not enabled or missing "type": "module" | Add "type": "module" to package.json and tsconfig.json |
| State doesn’t update the DOM | Variable declared as plain let instead of $state | Change declaration to $state(value) |
| Effects run on mount but not on updates | Effect captures stale dependencies due to labels | Use $effect and explicit read/write pairs |
| CSS not scoped | Global selectors leak across components | Rely on Vite’s automatic hashing; avoid custom :global() unless necessary |
Real-World Examples
1. Initialising a new project
mkdir demo && cd demo && npm init -y && npm i svelte vite && npm i -D ts-node typescript
2. Adding a component
echo '<script>let x = $state(0)</script>' > src/Multi.svelte
3. Running the dev server
npm run dev
Open http://localhost:5173 — you see the live counter.
4. Building for production
npm run build
Inspect dist/Multi.js for the emitted effect calls.
5. Previewing changes
npm run preview
See the updated DOM instantly.
6. Configuring TypeScript
npx tsc --init # creates tsconfig.json
7. Using sv watch
npm run sv-watch # (if installed) watches and reloads on save
8. Importing CSS
Place a .css file in public/css; Vite will copy it and link it.
9. Dynamic imports
{#import Component as Modal}
<Modal />
{/each}
10. Deploying
After npm run build, push the dist folder to your hosting platform; the static site is served directly.
Visual
Build Pipeline Diagram
┌─────────────────────┐
│ .svelte source │
│ (plain markup) │
└──────────┬──────────┘
▼
┌─────────────────────┐
│ Vite dev server │
│ (HMR, ESM) │
└──────────┬──────────┘
▼
┌─────────────────────┐
│ sv build / preview │
│ (run sv CLI) │
└──────────┬──────────┘
▼
Dist folder (production)
Signal Flow in Counter
count (signal) ──► set_text(node) ──► button click (event) ──► increment()
▲
│
doubled (derived) ──► set_text(node) ──► button label
Compiled Output Highlights
$.state(0)→ reactive source.$.derived(...)→ lazy recomputation.$.set(count, ...)→ write.$.listen(...)→ event binding.$.effect(...)→ side effect scheduled.
Summary
| Item | Value |
|---|---|
| Core idea | Vite + sv turn Svelte 2 markup into plain JS via a compiler; sv is the CLI wrapper. |
| Build command | npm run build → sv build |
| Dev command | npm run dev → Vite dev server with HMR |
| Preview command | npm run preview → local preview server |
| TypeScript | Enabled via "type": "module" and tsconfig.json |
| Reactivity primitives | $state, $derived, $effect, $props (runes) |
| Output size | Minimal; only DOM nodes touched by state changes |
Key takeaways:
- Vite gives you instant feedback through HMR, while
svgives you a clean build/preview command. - TypeScript is first class; the compiler enforces strict typing and ESM interoperability.
- Runes replace labels, making reactivity predictable and easier to debug.
- Only the affected DOM nodes are rewritten; the compiled code contains no diffing loop.
- Escape hatches exist (
{@html},<svelte:component>) but are limited to trusted content.
Remember: The magic happens in the build step. Write declarative Svelte templates, let Vite and the sv CLI translate them into imperative DOM operations, and you get a performant, type‑safe UI with virtually zero runtime overhead. Start with a tiny component, run npm run dev, hit npm run build, and watch the difference between a virtual‑DOM framework and a compiler‑driven system.
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!