EthicsComputerCourses
Join training +91 90532 10052

Vue 3 Front End with Vite

MEVN Stack · Lesson 9 of 20 Intermediate 10 min read Updated

By the end of this lesson you will understand what Vite does while you develop and when you build, how a .vue single-file component is put together, and how the NoteNest client turns into a few static files for production. You will write the first real component, NoteCard.vue, and show sample notes with it. The next lesson connects it to the API.

What you should know first: Set Up Your MEVN Environment, where create-vue made the client/ folder, and Project Structure for MEVN Apps. For Vue itself, see Components Basics, Props and Component Events & v-model; this lesson links those ideas to the stack instead of re-teaching them. Versions checked: Vue 3.5, Vite 8.3.8 and @vitejs/plugin-vue 6.0.11.

What Vite does for you

Browsers understand HTML, CSS and JavaScript. They do not understand .vue files, the @/ import alias or import.meta.env. Vite is the build tool that closes that gap. It works in two modes:

Development (npm run dev)Production (npm run build)
OutputNothing on disk; files are served from memoryA dist/ folder of static files
How code reaches the browserEach module separately, as native ES modulesBundled, minified files with hashed names
.vue filesCompiled one at a time, when the browser asksCompiled once, inside the bundle
After you save a fileHot Module Replacement swaps just that moduleRun the build again

Hot Module Replacement (HMR) replaces the changed component in the running page without a full reload, so the text you typed in a form usually survives. Think of a Pune food stall that cooks each order fresh when it is called (development), compared with a tiffin service that packs the whole day's meals in the morning (production). The first is quick to change; the second is quick to serve.

Under the hood, Vite 8 bundles with Rolldown and minifies CSS with Lightning CSS; both appear in Vite's own dependency list. You do not configure either for NoteNest.

Step 1: A quick tour of the scaffold

These are the files create-vue made, with their jobs:

Text
client/
├── index.html          the page shell; loads /src/main.js as a module
├── vite.config.js      plugins, the @ alias, and the /api proxy
├── .env.example        VITE_API_URL=/api
└── src/
    ├── main.js         creates the app, adds Pinia and the router, mounts it on #app
    ├── App.vue         the root component
    ├── api/            client.js, notes.js, auth.js (from earlier lessons)
    ├── components/     NoteCard.vue (this lesson)
    ├── router/         index.js (filled in the routing lesson)
    └── stores/         empty for now

index.html is the entry point, not a file Vite generates. It contains <div id="app"></div> and <script type="module" src="/src/main.js">. Make two fixes in it now: create-vue left <html lang=""> empty and the title as "Vite App". Change them to lang="en" and <title>NoteNest</title>. Screen readers use lang to choose a voice, and the title shows in the browser tab. Also delete src/stores/counter.js if it is still there, as the structure lesson said.

Step 2: Anatomy of a single-file component

A single-file component (SFC) keeps one piece of the screen in one .vue file with up to three blocks:

  • <script setup>: the logic. Everything you declare here is available in the template. setup means the Composition API with less boilerplate.
  • <template>: the HTML, with Vue's directives such as v-if, v-for and @click.
  • <style scoped>: CSS that applies only to this component.

Props are values a parent passes down into a component, like the address written on a parcel. Emits are events the component sends back up, like the delivery person ringing the bell. A component should never change its props directly; it emits an event and lets the owner of the data decide.

Step 3: Write NoteCard.vue

Create client/src/components/NoteCard.vue. The name has two words, as the style rules in the structure lesson require.

HTML
<!-- client/src/components/NoteCard.vue -->
<script setup>
import { computed } from 'vue'

const props = defineProps({
  note: { type: Object, required: true },
})
const emit = defineEmits(['togglePin', 'remove'])

const dateFormat = new Intl.DateTimeFormat('en-IN', { dateStyle: 'medium', timeZone: 'Asia/Kolkata' })
const updated = computed(() => dateFormat.format(new Date(props.note.updatedAt)))
</script>

<template>
  <article class="note-card" :class="{ pinned: note.pinned }">
    <h2>{{ note.title }}</h2>
    <p v-if="note.body">{{ note.body }}</p>
    <ul class="tags">
      <li v-for="tag in note.tags" :key="tag">{{ tag }}</li>
    </ul>
    <footer>
      <small>Updated {{ updated }}</small>
      <button type="button" @click="emit('togglePin', note)">
        {{ note.pinned ? 'Unpin' : 'Pin' }}
      </button>
      <button type="button" @click="emit('remove', note)">Delete</button>
    </footer>
  </article>
</template>

<style scoped>
.note-card {
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 12px;
}
.pinned {
  border-color: #42b883;
  background: #f0faf5;
}
.tags {
  display: flex;
  gap: 6px;
  padding: 0;
  list-style: none;
}
</style>

defineProps and defineEmits are compiler macros: Vite's Vue plugin understands them at build time, so you do not import them. The card expects a note in exactly the shape the API sends (id, title, body, tags, pinned, updatedAt). That is the API contract showing up in the front end. Dates come from the server in UTC, and the card formats them for India only when displaying, as in MongoDB & Mongoose Models.

The events are declared in camelCase (togglePin) and a parent listens in kebab-case (@toggle-pin). Vue converts between the two for you.

Step 4: Show sample notes in App.vue

Replace client/src/App.vue. For now the notes are a local array in the API's shape; the next lesson loads them from the server instead.

HTML
<!-- client/src/App.vue -->
<script setup>
import { ref, computed } from 'vue'
import NoteCard from '@/components/NoteCard.vue'

// Sample data in the API's shape. The next lesson loads it from the server.
const notes = ref([
  { id: 'a1', title: 'DBMS viva questions', body: 'Normal forms, keys, ACID', tags: ['college'], pinned: true, updatedAt: '2026-11-16T04:54:11.222Z' },
  { id: 'a2', title: 'Sunday groceries', body: 'Atta 5 kg, toor dal, curd', tags: ['home'], pinned: false, updatedAt: '2026-11-15T09:30:00.000Z' },
])

const sortedNotes = computed(() =>
  notes.value.toSorted(
    (a, b) => Number(b.pinned) - Number(a.pinned) || b.updatedAt.localeCompare(a.updatedAt),
  ),
)

function togglePin(note) {
  note.pinned = !note.pinned
}

function removeNote(note) {
  notes.value = notes.value.filter((n) => n.id !== note.id)
}
</script>

<template>
  <main class="notes-page">
    <h1>NoteNest</h1>
    <p v-if="notes.length === 0">No notes yet.</p>
    <NoteCard
      v-for="note in sortedNotes"
      :key="note.id"
      :note="note"
      @toggle-pin="togglePin"
      @remove="removeNote"
    />
  </main>
</template>

<style>
body {
  font-family: system-ui, sans-serif;
  margin: 0;
}
.notes-page {
  max-width: 40rem;
  margin: 0 auto;
  padding: 16px;
  display: grid;
  gap: 12px;
}
</style>

App.vue owns the data, so it is the one that changes pinned or removes a note when a card emits. The sort is the same rule the server uses: pinned first, then newest. The @/ in the import is the alias from vite.config.js, pointing at src/.

Step 5: See it in the browser

Run npm run dev (from the root or inside client/) and open the address Vite prints. We loaded the page in headless Chrome and read the page's innerText, which runs the date and the two buttons together (on screen they sit side by side):

Output
NoteNest
DBMS viva questions

Normal forms, keys, ACID

college
Updated 16 Nov 2026UnpinDelete
Sunday groceries

Atta 5 kg, toor dal, curd

home
Updated 15 Nov 2026PinDelete

The browser console also showed a warning from Vue Router that starts like this:

Output
[VUE_ROUTER_R0004] No match found for location with path "/"

That is expected: create-vue installed the router with an empty routes array. The warning goes away in Routing with Vue Router. Now change the border colour in NoteCard.vue and save. The card updates without a page reload; that is HMR at work.

You can try the same component without any build step. The Vue global build includes a template compiler, so a component can be a plain object with a template string. This is handy for experiments, but NoteNest itself uses .vue files, which Vite compiles ahead of time.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>NoteCard without a build step</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@3.5.44/dist/vue.global.prod.js"></script>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; max-width: 34rem; }
    .note-card { border: 1px solid #ccc; border-radius: 8px; padding: 12px; margin-bottom: 12px; }
    .pinned { border-color: #42b883; background: #f0faf5; }
    .tags { display: flex; gap: 6px; padding: 0; list-style: none; }
    .tags li { background: #eee; border-radius: 4px; padding: 0 6px; }
  </style>
</head>
<body>
  <div id="app"></div>

  <script>
    const { createApp, ref, computed } = Vue;
    const dateFormat = new Intl.DateTimeFormat("en-IN", { dateStyle: "medium", timeZone: "Asia/Kolkata" });

    // The same component as NoteCard.vue, written as an object
    const NoteCard = {
      props: { note: { type: Object, required: true } },
      emits: ["togglePin", "remove"],
      setup(props) {
        const updated = computed(() => dateFormat.format(new Date(props.note.updatedAt)));
        return { updated };
      },
      template: `
        <article class="note-card" :class="{ pinned: note.pinned }">
          <h2>{{ note.title }}</h2>
          <p v-if="note.body">{{ note.body }}</p>
          <ul class="tags"><li v-for="tag in note.tags" :key="tag">{{ tag }}</li></ul>
          <small>Updated {{ updated }}</small>
          <button type="button" @click="$emit('togglePin', note)">{{ note.pinned ? 'Unpin' : 'Pin' }}</button>
          <button type="button" @click="$emit('remove', note)">Delete</button>
        </article>`
    };

    createApp({
      components: { NoteCard },
      setup() {
        const notes = ref([
          { id: "a1", title: "DBMS viva questions", body: "Normal forms, keys, ACID", tags: ["college"], pinned: true, updatedAt: "2026-11-16T04:54:11.222Z" },
          { id: "a2", title: "Sunday groceries", body: "Atta 5 kg, toor dal, curd", tags: ["home"], pinned: false, updatedAt: "2026-11-15T09:30:00.000Z" },
          { id: "a3", title: "Train to Jaipur", body: "PNR 4521378690, coach B2", tags: ["travel", "home"], pinned: false, updatedAt: "2026-11-14T18:05:00.000Z" }
        ]);
        const sortedNotes = computed(() => notes.value.toSorted((a, b) =>
          Number(b.pinned) - Number(a.pinned) || b.updatedAt.localeCompare(a.updatedAt)));
        const togglePin = (note) => { note.pinned = !note.pinned; };
        const removeNote = (note) => { notes.value = notes.value.filter((n) => n.id !== note.id); };
        return { notes, sortedNotes, togglePin, removeNote };
      },
      template: `
        <h1>NoteNest</h1>
        <p v-if="notes.length === 0">No notes yet.</p>
        <NoteCard v-for="note in sortedNotes" :key="note.id" :note="note"
          @toggle-pin="togglePin" @remove="removeNote" />`
    }).mount("#app");
  </script>
</body>
</html>

Pin "Train to Jaipur" and it moves above "Sunday groceries", because pinned notes sort first (it stays below "DBMS viva questions", which is pinned too and newer). Delete all three and the "No notes yet." message appears.

Step 6: Build for production

Inside client/, run npm run build. Here is our real output:

Output
> client@0.0.0 build
> vite build

vite v8.3.8 building client environment for production...
transforming...
✓ 26 modules transformed.
rendering chunks...
computing gzip size...
dist/index.html                  0.43 kB │ gzip:  0.28 kB
dist/assets/index-CuP0dhEv.css   0.34 kB │ gzip:  0.23 kB
dist/assets/index-Bohf64Zk.js   92.05 kB │ gzip: 36.00 kB

✓ built in 2.89s

The whole client is now three files plus the favicon. The JavaScript includes Vue, Vue Router and Pinia, which is why it is 92 KB before compression. The odd part of each name, such as Bohf64Zk, is a content hash: it changes only when the file's content changes. A server can therefore tell browsers to cache /assets/* for a year, and a new build still reaches users at once, because index.html points at new names.

Look inside the CSS file and you can see how scoped works. Vite added a unique attribute to the component's selectors, and the same attribute to its elements:

Output
.note-card[data-v-e022ce5c]{border:1px solid #ccc;border-radius:8px;padding:12px}.pinned[data-v-e022ce5c]{background:#f0faf5;border-color:#42b883}...

So .pinned in NoteCard.vue can never style some other component's .pinned class. The global body rule from App.vue has no attribute, because that <style> block is not scoped.

To test the build locally, run npm run preview. It serves dist/ on http://localhost:4173/. The /api proxy from vite.config.js applies here too: with the API running, curl http://localhost:4173/api/health returned {"status":"ok"} for us. In real production, though, nothing proxies for you; Deploying a MEVN App shows how to serve dist/ and the API together.

Common mistakes

  • Opening dist/index.html by double-clicking. The page loads from file://, the absolute /assets/... paths break, and you see a blank page. Use npm run preview or a real web server.
  • Changing a prop inside the child. props.note.pinned = true in NoteCard.vue hides where data changes. Emit an event; let the parent change its own data.
  • One-word component names such as Card.vue. They can clash with HTML elements. Use NoteCard.vue.
  • Forgetting :key on v-for. Vue then reuses elements by position, and a deleted note can leave its state on the wrong card.
  • Putting secrets in .env.production with a VITE_ prefix. They ship to every visitor.

Interview questions

1. Why is the Vite dev server fast to start even for a big app?

It does not bundle the app before serving. The browser requests native ES modules, and Vite transforms each file only when it is requested, while dependencies are pre-bundled once. Production builds still bundle and minify everything.

2. What does scoped do in a Vue single-file component?

Vite's Vue plugin adds a unique data-v- attribute to the component's elements and rewrites its CSS selectors to require that attribute. The styles therefore affect only that component's own elements, plus the root element of a child component.

3. Why do production files have hashes in their names?

The hash comes from the file's content, so it changes only when the content changes. Servers can cache hashed assets for a long time, and users still get new code after a deploy because index.html references the new file names.

4. What is the difference between props and emits?

Props carry data from a parent into a child and should be treated as read-only. Emits let the child notify the parent that something happened, such as a click, so the parent can update its own state. Together they keep data flowing one way.

Key points

  • Vite serves native ES modules with HMR in development and builds hashed, minified files into dist/ for production; Vite 8 bundles with Rolldown.
  • index.html is the entry point; main.js creates the app; App.vue is the root component. Set lang="en" and a real title.
  • A .vue file has <script setup>, <template> and optional <style scoped>; defineProps and defineEmits are compiler macros.
  • NoteCard.vue receives a note in the API's shape and emits togglePin and remove; App.vue owns and changes the data.
  • scoped CSS works by adding a data-v- attribute; hashed file names make long caching safe.
  • Test builds with npm run preview, never by opening dist/index.html from disk.

Exercise

Split the tag list out of NoteCard.vue into a new component, NoteTags.vue. It receives a tags prop (an array of strings) and shows each tag as a button. Clicking a tag emits select with that tag. NoteCard should pass the event on as its own selectTag event, and App.vue should show "Showing tag: college" above the list and only the notes with that tag, plus a "Show all" button.

Show solution
HTML
<!-- client/src/components/NoteTags.vue -->
<script setup>
defineProps({ tags: { type: Array, default: () => [] } })
const emit = defineEmits(['select'])
</script>

<template>
  <ul class="tags">
    <li v-for="tag in tags" :key="tag">
      <button type="button" @click="emit('select', tag)">{{ tag }}</button>
    </li>
  </ul>
</template>

In NoteCard.vue, import it, add 'selectTag' to defineEmits, and replace the old list with <NoteTags :tags="note.tags" @select="emit('selectTag', $event)" />. In App.vue, add const tag = ref(''), filter inside the computed (.filter((n) => !tag.value || n.tags.includes(tag.value)) before sorting), listen with @select-tag="tag = $event", and show <p v-if="tag">Showing tag: {{ tag }} <button type="button" @click="tag = ''">Show all</button></p>. The data still lives in App.vue; both child components only emit.

Quick Quiz

1. What does Vite do with a .vue file during npm run dev?

2. Why does NoteCard emit togglePin instead of changing note.pinned itself?

3. What is the purpose of the hash in dist/assets/index-Bohf64Zk.js?

4. How should you check a production build on your machine?

Learn MEVN Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call