Vite with Vue
Vite was created by Evan You, the author of Vue, and Vue's official tooling is built on it. Vue single-file components (.vue files) are compiled by @vitejs/plugin-vue, with HMR that keeps component state.
Two ways to start
| Command | What you get |
|---|---|
npm create vite@latest app -- --template vue-ts |
Minimal Vue + TypeScript app |
npm create vue@latest |
Official Vue scaffolder (also Vite-based) with optional Router, Pinia, Vitest, ESLint, Playwright |
npm create vite@latest vue-notes -- --template vue-ts
cd vue-notes
npm install
npm run dev> npx
> create-vite vue-notes --template vue-ts
│
◇ Scaffolding project in /home/me/vue-notes...
│
└ Done.
added 48 packages, and audited 49 packages in 6s
found 0 vulnerabilities
> vue-notes@0.0.0 dev
> vite
VITE v8.3.4 ready in 356 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h + enter to show help
The config
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
});Optional companions: @vitejs/plugin-vue-jsx for JSX/TSX in Vue, and vite-plugin-vue-devtools for in-page devtools.
A single-file component
<!-- src/components/NoteList.vue -->
<script setup lang="ts">
import { ref, computed } from 'vue';
const notes = ref<string[]>(['Learn Vite', 'Try HMR']);
const draft = ref('');
const count = computed(() => notes.value.length);
function add() {
if (draft.value.trim()) notes.value.push(draft.value.trim());
draft.value = '';
}
</script>
<template>
<h2>Notes ({{ count }})</h2>
<input v-model="draft" @keyup.enter="add" placeholder="New note" />
<ul>
<li v-for="note in notes" :key="note">{{ note }}</li>
</ul>
</template>
<style scoped>
h2 { color: #42b883; }
</style>// src/main.ts
import { createApp } from 'vue';
import './style.css';
import App from './App.vue';
createApp(App).mount('#app');How a .vue file is compiled
The plugin splits each SFC into blocks and turns each into normal modules:
| Block | Becomes |
|---|---|
<script setup> |
The component's setup function (TypeScript stripped) |
<template> |
A compiled render function — no template compiler shipped to the browser |
<style scoped> |
CSS where selectors get a unique attribute like [data-v-7a3f2c1b] |
<style module> |
A CSS Module available as $style |
Scoped styles work by adding a data attribute to the component's elements and to every selector. This playground performs that rewrite:
function scopeCss(css, scopeId) {
return css.replace(/([^{}\n]+)\{/g, (_, selectors) =>
selectors
.split(',')
.map((s) => `${s.trim()}[data-v-${scopeId}]`)
.join(', ') + ' {'
);
}
console.log(scopeCss('h2 { color: #42b883; }\n.item, li { padding: 4px; }', '7a3f2c1b'));h2[data-v-7a3f2c1b] { color: #42b883; }
.item[data-v-7a3f2c1b], li[data-v-7a3f2c1b] { padding: 4px; }
And here is that scoping effect in a live page — only elements carrying the component's attribute are styled:
<!doctype html>
<html>
<head>
<style>
body { font-family: system-ui; padding: 1rem; }
h2[data-v-7a3f2c1b] { color: #42b883; }
</style>
</head>
<body>
<h2 data-v-7a3f2c1b>Inside NoteList.vue (scoped green)</h2>
<h2>Another component's h2 (unaffected)</h2>
</body>
</html>Reactivity, in plain JavaScript
Vue's ref and computed are runtime features, not compiler magic. A tiny imitation with getters and setters shows the idea of tracking reads and re-running effects on writes:
let activeEffect = null;
function ref(value) {
const subs = new Set();
return {
get value() { if (activeEffect) subs.add(activeEffect); return value; },
set value(v) { value = v; subs.forEach((fn) => fn()); },
};
}
function watchEffect(fn) { activeEffect = fn; fn(); activeEffect = null; }
const notes = ref(['Learn Vite']);
watchEffect(() => console.log(`render: Notes (${notes.value.length})`));
notes.value = [...notes.value, 'Try HMR'];
notes.value = [...notes.value, 'Ship it'];render: Notes (1)
render: Notes (2)
render: Notes (3)
Useful Vue-specific config
import { fileURLToPath, URL } from 'node:url';
export default defineConfig({
plugins: [
vue({
template: {
compilerOptions: {
isCustomElement: (tag) => tag.startsWith('ion-'), // treat as web components
},
},
}),
],
resolve: {
alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) },
},
});Type-checking .vue files
tsc cannot read .vue files. Vue templates use vue-tsc instead, which is why the build script is:
{ "scripts": { "build": "vue-tsc -b && vite build" } }Tip: Install the "Vue (Official)" VS Code extension for template type checking and autocompletion.
Test yourself
Which plugin compiles .vue single-file components?
- @vitejs/plugin-react
- @vitejs/plugin-vue
- vue-loader
- @vue/cli
How do <style scoped> rules avoid affecting other components?
- They are placed in a Shadow DOM
- Selectors get a unique
data-v-xxxxattribute - They are inlined as style attributes
- They are deleted at build time
Which command type-checks Vue templates and scripts?
- tsc
- vite check
- vue-tsc
- eslint