TExcelTAD
Home › Vite › Vite Build for Production

Vite Build for Production

In development Vite serves unbundled modules. For production you run vite build, which bundles, transforms and minifies everything into a folder of static files — dist/ — ready to upload to any web server or CDN.

Running a build

bash · try it yourself
npm run build
> my-app@0.0.0 build
> vite build

vite v8.3.4 building client environment for production...
✓ 5 modules transformed.
dist/index.html                  0.46 kB │ gzip: 0.30 kB
dist/assets/index-DiwrgTda.css   1.24 kB │ gzip: 0.63 kB
dist/assets/index-C3k9pQ2x.js    3.10 kB │ gzip: 1.48 kB
✓ built in 140ms

The report lists every output file with its raw and gzip size. Gzip size is roughly what users actually download, so watch that column.

What the build does

Step Detail
Start at index.html Every <script type="module"> and stylesheet is an entry
Resolve & transform Same plugin pipeline as dev: TS, JSX, Vue/Svelte, CSS Modules, env replacement
Bundle Rolldown combines modules into chunks and tree-shakes unused exports
Code-split Each dynamic import() becomes its own chunk; shared code is extracted
Minify JS with Oxc (default), CSS with Lightning CSS
Hash file names index-C3k9pQ2x.js — for long-term caching
Rewrite HTML Inserts <script>/<link> tags and modulepreload hints with the hashed names
Copy public/ Files copied unchanged into dist/

Tree-shaking

Bundlers only keep code that is actually reachable from the entry. If utils.js exports ten functions and you import one, the other nine are dropped. The playground simulates the reachability analysis on a tiny module graph:

js · try it yourself
const modules = {
  'main.js':  { imports: { 'utils.js': ['formatPrice'] } },
  'utils.js': {
    exports: {
      formatPrice: ['round'],      // formatPrice uses round internally
      round: [],
      slugify: [],
      debounce: [],
    },
  },
};

const used = new Set();
function mark(name) {
  if (used.has(name)) return;
  used.add(name);
  modules['utils.js'].exports[name].forEach(mark);
}
modules['main.js'].imports['utils.js'].forEach(mark);

const all = Object.keys(modules['utils.js'].exports);
console.log('kept:   ', all.filter((n) => used.has(n)).join(', '));
console.log('dropped:', all.filter((n) => !used.has(n)).join(', '));
kept:    formatPrice, round
dropped: slugify, debounce

Tip: Tree-shaking only works with ES module import/export. Prefer ESM packages like lodash-es over CommonJS ones like lodash.

Important build options

js
// vite.config.js
import { defineConfig } from 'vite';

export default defineConfig({
  build: {
    outDir: 'dist',             // output folder
    assetsDir: 'assets',        // sub-folder for JS/CSS/assets
    emptyOutDir: true,          // clean outDir first (default when it's inside root)
    target: 'baseline-widely-available', // default browser target
    sourcemap: false,           // true | 'inline' | 'hidden'
    minify: 'oxc',              // 'oxc' (default) | 'terser' | false
    cssCodeSplit: true,         // CSS per async chunk
    assetsInlineLimit: 4096,    // inline assets smaller than 4 KiB
    chunkSizeWarningLimit: 500, // kB, warn above this
    manifest: false,            // emit .vite/manifest.json for backend integration
  },
});
Option When to change it
target Supporting older browsers ('es2020', ['chrome90', 'safari14']) or only modern ones ('esnext')
sourcemap 'hidden' to upload maps to an error tracker without exposing them
minify: false Debugging production-only issues
outDir Your host expects build/ or public_html/
manifest A back end (Laravel, Rails, Django…) renders HTML and needs to know the hashed names

Browser target

baseline-widely-available means "features that have been supported in all major browsers for at least 30 months". Syntax newer than the target is lowered (for example ??= may be rewritten). Vite does not add polyfills for missing APIs — use @vitejs/plugin-legacy if you must support very old browsers.

Watch mode

vite build --watch rebuilds when files change — useful for browser extensions or when another server serves dist/:

bash · try it yourself
npx vite build --watch
vite v8.3.4 building client environment for production...

watching for file changes...

build started...
✓ 5 modules transformed.
dist/index.html                  0.46 kB │ gzip: 0.30 kB
dist/assets/index-DiwrgTda.css   1.24 kB │ gzip: 0.63 kB
dist/assets/index-C3k9pQ2x.js    3.10 kB │ gzip: 1.48 kB
built in 138ms.

Minification, visualized

Minifiers rename local variables, remove whitespace and comments, and fold constants. A toy minifier shows why the output is so small (real minifiers parse the code properly — never use regexes for this!):

js · try it yourself
const source = `
// format a price for display
function formatPrice(amount) {
  const rounded = Math.round(amount * 100) / 100;
  return '
  

 + rounded.toFixed(2);
}
`;

const minified = source
  .replace(/\/\/.*$/gm, '')
  .replace(/\brounded\b/g, 'r')
  .replace(/\bamount\b/g, 'a')
  .replace(/\s*([(){};=+*/,])\s*/g, '$1')
  .replace(/\s+/g, ' ')
  .trim();

console.log(minified);
console.log(`${source.length} -> ${minified.length} chars`);
function formatPrice(a){const r=Math.round(a*100)/100;return '
  

+r.toFixed(2);}
149 -> 79 chars

Checking the result

Never deploy a build you haven't looked at. The next lesson covers vite preview, which serves dist/ locally exactly as a static host would.

Test yourself

Which bundler does vite build use in Vite 8?

  1. esbuild
  2. webpack
  3. Rolldown
  4. Parcel

What does tree-shaking remove?

  1. Comments only
  2. Exports that are never imported or reached
  3. Unused CSS files in public/
  4. Old builds in dist/

Does Vite add polyfills for missing browser APIs by default?

  1. Yes, always
  2. No; it lowers syntax to the target, polyfills need @vitejs/plugin-legacy or manual imports
  3. Only for Promise
  4. Only in dev