Frontend development · Beginner · 22 min
Start and build a plain JavaScript project with Vite 8
By Padding · Updated 18 Nov 2026
Node.js 26 · Vite 8.3.8 · create-vite 9.3.4 · checked in the node:26 image
You will scaffold a plain JavaScript project with Vite 8, watch hot updates in the dev server, import CSS and an image, read VITE_ settings, serve fixed files from public, and ship a hashed production build that works from a sub-folder.
On this page
Vite is the build tool behind most new JavaScript front ends, but people usually meet it through a framework template and never see what it does on its own. This tutorial uses the plain JavaScript (vanilla) template, with no framework, so every behaviour you see belongs to Vite itself.
Vite works in two modes. In development it serves your source files to the browser as native ES modules, transforming each one on request, so the server starts in well under a second however large the project gets. For production, vite build bundles and minifies everything into a dist folder of plain static files with content hashes in their names, ready for any web server or CDN.
You will build a one-page site for a fictional bookshop, Kanda Books, step by step: a page that imports its stylesheet and logo from JavaScript, takes its name and opening hours from a settings file, offers a downloadable text file, and is then built, previewed and moved under a /shop/ sub-folder. The last step tests the built site in a real browser with Playwright.
All commands run on macOS or Linux in a terminal. On Windows, use WSL or Git Bash.
Step 1 · Scaffold the vanilla template
npm create vite downloads create-vite and runs it. Pin its version so you get the same template as this tutorial, choose the vanilla template, and pass --no-interactive so it asks no questions. The double dash hands the options to create-vite rather than to npm. Then install the dependencies:
cd ~
npm create vite@9.3.4 vite-demo -- --template vanilla --no-interactive
cd vite-demo
npm install
npm ls vite
lsThe template's package.json asks for vite in the 8.3 range, and npm install records the exact version it chose in package-lock.json. Commit that lock file in a real project, so everyone on the team and your deploy pipeline build with the same Vite.
Look at what you got. index.html sits at the top of the project, not inside public or src. That is deliberate: in Vite the HTML page is the entry point. Vite reads it, follows its <script type="module"> tag to src/main.js, and follows the imports from there. The package.json scripts are short: dev runs vite, build runs vite build and preview runs vite preview.
Check it worked
npm ls vite prints a tree ending in vite@8.3. followed by a patch number (8.3.8 or later). ls lists index.html, node_modules, package-lock.json, package.json, public and src.
Step 2 · Replace the starter with a page that imports CSS and an image
The starter draws a counter and links to Vite's community pages. You do not need either. The next command deletes the starter's counter, its sample images and an icon sprite. These are files the template has just created, so nothing of yours is lost:
rm -rf src/counter.js src/assets public/icons.svg
mkdir -p src/assetsWrite the page. It is nearly empty, because JavaScript fills in the content:
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Kanda Books</title>
</head>
<body>
<main id="app"></main>
<script type="module" src="/src/main.js"></script>
</body>
</html>
HTMLAdd a stylesheet and a small logo:
cat > src/style.css <<'CSS'
body {
margin: 0;
background: #fafaf9;
color: #1c1917;
font-family: system-ui, sans-serif;
line-height: 1.5;
}
main { max-width: 32rem; margin: 0 auto; padding: 1.5rem 1rem; }
.masthead { display: flex; align-items: center; gap: 0.75rem; }
.masthead h1 { margin: 0; font-size: 1.75rem; }
.mode { color: #57534e; font-size: 0.875rem; }
CSS
cat > src/assets/logo.svg <<'SVG'
<svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" viewBox="0 0 56 56">
<rect width="56" height="56" rx="12" fill="#c2410c"/>
<path d="M14 16h12a4 4 0 0 1 4 4v22a3 3 0 0 0-3-3H14z" fill="#fff7ed"/>
<path d="M42 16H30a4 4 0 0 0-4 4v22a3 3 0 0 1 3-3h13z" fill="#ffedd5"/>
</svg>
SVGNow the script. It imports both files:
cat > src/main.js <<'JS'
import './style.css'
import logoUrl from './assets/logo.svg'
document.querySelector('#app').innerHTML = `
<header class="masthead">
<img class="logo" src="${logoUrl}" alt="" width="56" height="56">
<h1>Kanda Books</h1>
</header>
<p class="hours">Open Monday to Saturday, 09:00 to 18:00.</p>
`
JSNeither import is standard JavaScript. A browser on its own cannot import a .css or .svg file this way. Vite makes them work:
import './style.css'adds the stylesheet to the page. In development Vite injects it as a<style>tag. In the build it becomes a separate, minified.cssfile linked from the HTML.import logoUrl from './assets/logo.svg'gives you a URL for the file, not its contents. In development that is a path such as/src/assets/logo.svg. In the build it becomes either a hashed file name or, for small files, the image itself written inline as adata:URL. You will see which in the build step.
Because the file is imported, Vite knows the page depends on it. If you misspell the path, Vite reports an error instead of shipping a broken image.
The logo has empty alt text because the shop name sits right next to it, so a screen reader would only repeat it.
Check it worked
ls src src/assets lists assets, main.js and style.css in src, and logo.svg in src/assets. The next step shows the page in a browser.
Step 3 · Run the dev server and watch hot updates
Start the development server:
npm run devVite prints a Local: address, http://localhost:5173/. Open it in your browser and leave the terminal running. Do the rest of this step from a second terminal in the same folder (cd ~/vite-demo).
To try the page on a phone, for example a low-end Android handset on the same Wi-Fi, stop the server and start it with npm run dev -- --host. Vite then also prints a Network: address you can type into the phone's browser. Only do this on a network you trust, because anyone on it can reach the server.
Now change the stylesheet while the page is open. This appends one rule that gives the page a warm background:
cat >> src/style.css <<'CSS'
body { background: #fff4e5; }
CSSThe colour changes in the browser without the page reloading. This is hot module replacement (HMR): Vite noticed the file change, sent the new CSS over a WebSocket, and its small client script in the page swapped the old styles for the new ones. Anything you had typed into a form, or how far you had scrolled, stays as it was.
Now change the JavaScript. Append a line that updates the opening hours:
cat >> src/main.js <<'JS'
document.querySelector('.hours').textContent = 'Open Monday to Saturday, 08:30 to 18:00.'
JSThis time the whole page reloads. CSS files know how to replace themselves, but plain JavaScript modules do not: nothing in main.js says how to swap in a new version of it while the page is running, so Vite falls back to a full reload. Frameworks such as React and Vue add that knowledge through their Vite plugins, which is why their components update in place.
Check it worked
The page shows the orange book logo, the heading Kanda Books and the opening hours. After the CSS edit the background turns a light peach colour with no flash of a reload. After the JavaScript edit the page flashes briefly and the hours read 08:30 to 18:00. The terminal running Vite logs a line for each change: an hmr update for /src/style.css, then a page reload for src/main.js (the exact wording varies between versions).
Step 4 · Pass settings in with VITE_ environment variables
Settings that change between environments, such as a shop name per branch or an API address per server, belong in .env files rather than in your code. Vite reads .env from the project folder when it starts, and exposes variables whose names start with VITE_ on import.meta.env. Variables without the prefix are left out on purpose. Create the file with two public settings and one that should stay private:
cat > .env <<'ENV'
VITE_SHOP_NAME=Kanda Books Kisumu
VITE_HOURS=Monday to Saturday, 08:30 to 18:00
SHOP_ADMIN_NOTE=only-for-build-scripts
ENVRewrite src/main.js to use them. The overwrite also removes the line you appended in the last step, because the hours now come from .env:
cat > src/main.js <<'JS'
import './style.css'
import logoUrl from './assets/logo.svg'
const shopName = import.meta.env.VITE_SHOP_NAME ?? 'Our shop'
const hours = import.meta.env.VITE_HOURS ?? 'see the shop door'
document.querySelector('#app').innerHTML = `
<header class="masthead">
<img class="logo" src="${logoUrl}" alt="" width="56" height="56">
<h1></h1>
</header>
<p class="hours"></p>
<p class="mode">Built in ${import.meta.env.MODE} mode</p>
`
document.querySelector('h1').textContent = shopName
document.querySelector('.hours').textContent = `Open ${hours}.`
console.log('SHOP_ADMIN_NOTE is', import.meta.env.SHOP_ADMIN_NOTE)
JSThe settings are set with textContent rather than pasted into the HTML string, so a value containing < or & is shown as text and never parsed as markup. import.meta.env.MODE is one of the values Vite always provides: development under npm run dev and production in a build. import.meta.env.BASE_URL is another, and you will use it in the next step.
Stop the dev server with Ctrl+C and start it again, so it is sure to read the new file:
npm run devOne rule matters more than the rest. Every VITE_ value is copied into the JavaScript that ships to the browser, where anyone can read it. That is fine for a shop name, a public API address or a map style ID. It is never fine for a password, a private API key or a database URL. Keep those on a server, and have the browser call that server instead. The prefix is Vite's way of making you opt in to publishing a value, and you will see the proof in the build step.
Two more details. Values in .env are always strings, so VITE_SHOW_BANNER=false arrives as the text "false", which counts as true in an if. And the template's .gitignore ignores files ending in .local, so a .env.local file is the place for values that belong to your machine and should not be committed. It overrides .env when both set the same name.
Check it worked
Reload http://localhost:5173/. The heading reads Kanda Books Kisumu, the hours read Open Monday to Saturday, 08:30 to 18:00., and a grey line below says Built in development mode. Open the browser's developer tools console: it shows SHOP_ADMIN_NOTE is undefined.
Step 5 · Serve fixed files from the public folder
Some files must keep their exact name and path: robots.txt, a favicon, a file people download or link to from elsewhere. Those go in the public folder. Vite serves them at the root of the site in development and copies them unchanged, with no hash, into the build.
Add a downloadable text file, and replace the template's favicon, which is Vite's own logo, with the shop's:
cat > public/opening-hours.txt <<'TXT'
Kanda Books Kisumu
Monday to Saturday: 08:30 to 18:00
Sunday: closed
TXT
cp src/assets/logo.svg public/favicon.svgLink to the text file from the page. Do not import files from public in JavaScript; refer to them by URL. Build that URL from import.meta.env.BASE_URL, which is / for now, so the link keeps working when the site moves to a sub-folder later:
cat >> src/main.js <<'JS'
const download = document.createElement('a')
download.href = `${import.meta.env.BASE_URL}opening-hours.txt`
download.textContent = 'Opening hours as a text file'
document.querySelector('#app').append(download)
JSUse public only for files that need a fixed name. Everything else, like the logo, is better imported: imported files get hashed names, which lets browsers cache them for a long time, and Vite tells you when one is missing.
Check it worked
Fetch the file from the running dev server:
curl -s http://localhost:5173/opening-hours.txtIt prints the three lines of opening hours. In the browser the page reloads with a link, Opening hours as a text file, under the mode line, and the browser tab now shows the orange book icon. You may need a hard reload, because browsers cache favicons.
Step 6 · Build for production and read what lands in dist
Stop the dev server with Ctrl+C. You do not need it to build. Run the build and list what it wrote:
npm run build
ls dist dist/assetsVite prints each output file with its size and its gzip size. The gzip figure is close to what a visitor actually downloads, which matters when they pay for data by the megabyte. Your listing looks something like this, with different hash letters:
dist:
assets favicon.svg index.html opening-hours.txt
dist/assets:
index-B047ULKw.js index-qARpA1QZ.cssFour things to notice:
- Hashed names. The part after
index-is a hash of the file's contents. Change one character of CSS and the CSS file gets a new name. That lets a server tell browsers to cache everything inassetsfor a year: a new release always has new names, so nobody gets stale code. - The public files (
favicon.svg,opening-hours.txt) sit at the top ofdistwith their names unchanged. - No logo file. The logo is under 4 KiB, Vite's default inline limit, so it was written straight into the JavaScript as a
data:URL. That saves a request. Larger images, such as photos, become hashed files inassets. To keep one small file separate, import it with?no-inlineon the end of the path. dist/index.htmlnow points at the hashed files instead of/src/main.js.
Check the last point, and prove what happened to each environment variable:
grep -o 'assets/index-[^"]*' dist/index.html
grep -c 'data:image/svg+xml' dist/assets/*.js
grep -l 'Kanda Books Kisumu' dist/assets/*.js
if grep -rq 'only-for-build-scripts' dist; then echo "SHOP_ADMIN_NOTE leaked"; else echo "SHOP_ADMIN_NOTE is not in dist"; fiThen build again without changing anything, and compare the file names:
ls dist/assets > first-build.txt
npm run build > /dev/null
ls dist/assets | diff first-build.txt - && echo "same file names"Check it worked
The first grep prints two paths, one ending in .js and one in .css. The second prints 1: the logo is inside the JavaScript. The third prints the JavaScript file's path: the shop name, a VITE_ value, is in plain text in the code you ship. The last line prints SHOP_ADMIN_NOTE is not in dist. The rebuild prints same file names, because the same input gives the same hashes.
Step 7 · Preview the build and set base for a sub-folder
Opening dist/index.html straight from the disk does not work, because module scripts do not load from file:// addresses. Serve the folder instead:
npm run previewvite preview serves dist at http://localhost:4173/. It is a quick local check that the build works, not a production server; in production, any static file server or host can serve dist. Open the address: the page looks the same as before, except the grey line now says Built in production mode.
So far the site assumes it lives at the root of a domain. Many hosts put it in a sub-folder instead, such as a GitHub Pages project site at https://<user>.github.io/<repo>/, or a shop page under /shop/ on an existing site. Every /assets/... link would then point at the wrong place. The base option tells Vite the path the site will be served from. The template has no config file yet, so create one:
cat > vite.config.js <<'JS'
import { defineConfig } from 'vite'
export default defineConfig({
base: '/shop/',
})
JS
npm run build
grep -E 'shop/' dist/index.htmlVite rewrote the script, stylesheet and favicon links in dist/index.html to start with /shop/. In your JavaScript, import.meta.env.BASE_URL is now /shop/ too, which is why the text-file link was built from it in the last step. A hard-coded /opening-hours.txt would now be broken. For a one-off build you can also pass the value on the command line, as npx vite build --base=/shop/.
Stop the preview server with Ctrl+C and start it again, so it serves the new build:
npm run previewCheck it worked
The grep prints three lines, each with /shop/ in it: the favicon, the script and the stylesheet. Preview now serves the site at http://localhost:4173/shop/. Open it and the page works as before. From your second terminal, fetch the text file at its new path:
curl -s http://localhost:4173/shop/opening-hours.txtIt prints the three lines of opening hours.
Step 8 · Test the built site in a browser with Playwright
Looking at the page once is easy. A test that loads the built site in a real browser catches a broken base, a missing file or a lost environment variable every time you build. Leave the preview server running, and from your second terminal install Playwright and the Chromium browser it drives. On Linux, --with-deps also installs the system libraries Chromium needs, and may ask for your password:
npm install --save-dev playwright@1.65.1
npx playwright install --with-deps chromiumWrite a test that opens the sub-folder address and checks what a visitor would get:
cat > check-build.mjs <<'JS'
import { chromium } from 'playwright'
import assert from 'node:assert/strict'
const site = 'http://localhost:4173/shop/'
const browser = await chromium.launch()
const page = await browser.newPage()
// Record every file the page asks for that fails.
const failed = []
page.on('response', (r) => { if (r.status() >= 400) failed.push(`${r.status()} ${r.url()}`) })
await page.goto(site)
// The VITE_ values and the production mode reached the page.
await page.getByRole('heading', { name: 'Kanda Books Kisumu' }).waitFor()
assert.equal(await page.locator('.hours').textContent(), 'Open Monday to Saturday, 08:30 to 18:00.')
assert.equal(await page.locator('.mode').textContent(), 'Built in production mode')
// The imported CSS is applied, with the rule added during the HMR step.
const bg = await page.evaluate(() => getComputedStyle(document.body).backgroundColor)
assert.equal(bg, 'rgb(255, 244, 229)')
// The logo was inlined by the build and it loaded.
const logo = page.locator('img.logo')
assert.match(await logo.getAttribute('src'), /^data:image\/svg\+xml/)
assert.ok(await logo.evaluate((img) => img.complete && img.naturalWidth > 0), 'logo loaded')
// The public file is linked under /shop/ and can be downloaded.
const link = page.getByRole('link', { name: 'Opening hours as a text file' })
const href = await link.getAttribute('href')
assert.equal(href, '/shop/opening-hours.txt')
const text = await (await page.request.get(new URL(href, site).href)).text()
assert.match(text, /Sunday: closed/)
// The favicon path was rewritten for the sub-folder.
assert.equal(await page.locator('link[rel="icon"]').getAttribute('href'), '/shop/favicon.svg')
assert.deepEqual(failed, [], 'no failed requests')
await browser.close()
console.log('PASS: the build works under /shop/')
JS
node check-build.mjsThe test finds the heading and the link by role and name, the same way assistive technology finds them, and listens for any request that fails, which is how a wrong base usually shows up.
Check it worked
The last line of output is PASS: the build works under /shop/. To see it fail for the right reason, change base in vite.config.js to '/', run npm run build, restart the preview server and run node check-build.mjs again: it stops with an AssertionError, because the text-file link now points at /opening-hours.txt instead of /shop/opening-hours.txt. Put '/shop/' back, build, restart the preview and the test passes again.
Step 9 · Clean up
Stop the preview server with Ctrl+C in its terminal. Then delete the project, which also removes the local Playwright package. The Chromium browser Playwright downloaded stays in a shared cache; run npx playwright uninstall from the project folder first if you want that gone too.
cd ~
rm -rf ~/vite-demoCheck it worked
ls ~/vite-demo reports that there is no such file or directory, and http://localhost:4173/shop/ no longer loads.
Next steps
- Go back to what Vite builds on with JavaScript modules with import and export, or see how far the browser gets with no build step at all in load ES modules without a bundler using import maps.
- Add a utility-first stylesheet to a project like this one in set up Tailwind CSS 4 with Vite.
- Use the same tool with a framework in build a React 19 app with Vite, where components update in place instead of reloading.
Part of these paths
Related tutorials
- How to Build a React 19 App with ViteYou will scaffold a React 19 and TypeScript app with Vite 8, run the dev server, replace the starter page with a small checklist built from components and state, then create a production build and serve it locally.
- How to Set Up Tailwind CSS 4 with ViteYou will add Tailwind CSS 4.3 to a new Vite 8 project with its official Vite plugin, style a card with utility classes, add your own brand colour with @theme, use the dark and responsive variants, and check in the production build that only the classes you use are generated.
- Use JavaScript modules with import and exportYou will split a Node.js bill-splitting script into three ES modules with named and default exports, load built-ins and code on demand, recognise CommonJS and its errors, and run the same modules in a browser.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials