TExcelTAD
Home › Vite › Vite ES Modules Primer

Vite ES Modules Primer

Vite is built on ES modules (ESM), the standard module system of JavaScript. If you understand how import and export behave, most of Vite's design suddenly makes sense.

Named and default exports

A module is a file with its own scope. Only what it exports is visible to others.

js
// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }
export default function hello(name) { return `Hello, ${name}`; }
js
// main.js
import hello, { area, PI as pi } from './math.js';
import * as math from './math.js';
Syntax Meaning
export const x / export function f Named export
export default value One default export per module
import { x } from './m.js' Import a named export
import x from './m.js' Import the default export
import { x as y } Rename on import
import * as ns Namespace object with all exports
export { x } from './m.js' Re-export (barrel files)
import './side-effect.js' Run a module for its side effects only (e.g. CSS)

Trying it live

These playgrounds create modules from strings with data: URLs and load them with dynamic import(), so you can experiment without files.

js · try it yourself
const source = `
  export const PI = 3.14159;
  export function area(r) { return +(PI * r * r).toFixed(2); }
  export default function hello(name) { return 'Hello, ' + name; }
`;
const url = 'data:text/javascript,' + encodeURIComponent(source);

(async () => {
  const mod = await import(url);
  console.log(mod.default('Vite'));
  console.log('area(2) =', mod.area(2));
  console.log('exports:', Object.keys(mod).join(', '));
})();
Hello, Vite
area(2) = 12.57
exports: PI, area, default

Modules run once and are cached

No matter how many times a module is imported, it is evaluated once per URL. Every importer gets the same instance — that is why a module-level variable works as shared state.

js · try it yourself
const counterSrc = `
  console.log('counter module evaluated');
  let n = 0;
  export const next = () => ++n;
`;
const url = 'data:text/javascript,' + encodeURIComponent(counterSrc);

(async () => {
  const a = await import(url);
  const b = await import(url);
  console.log('same instance?', a === b);
  a.next(); a.next();
  console.log('b.next() returns', b.next());
})();
counter module evaluated
same instance? true
b.next() returns 3

Note: This is also why Vite appends ?v=hash or ?t=timestamp to URLs during HMR — a different URL means a fresh module instance.

Live bindings

Imports are live views of the exporter's variables, not copies. When the exporting module changes a let, importers see the new value. Importers themselves cannot reassign an import.

js · try it yourself
'use strict'; // module code is always strict; this classic script opts in
const src = `
  export let status = 'idle';
  export function start() { status = 'running'; }
`;
const url = 'data:text/javascript,' + encodeURIComponent(src);

(async () => {
  const m = await import(url);
  console.log('before:', m.status);
  m.start();
  console.log('after:', m.status);
  try {
    m.status = 'hacked';
  } catch (err) {
    console.log('cannot assign:', err.constructor.name);
  }
})();
before: idle
after: running
cannot assign: TypeError

Static vs dynamic import

import x from '...' await import('...')
Where Top level only Anywhere (functions, conditions)
When resolved Before the module runs At runtime
Analyzable by bundler Fully (tree-shaking) Becomes a separate chunk
Returns Bindings A Promise of the namespace object

Static imports let Vite and Rolldown drop unused exports (tree-shaking). Dynamic imports are the basis of code splitting, covered in the Production section.

Bare imports and why Vite rewrites them

Browsers only accept URLs: ./a.js, /src/a.js or https://.... A bare specifier like import { ref } from 'vue' fails in a plain browser. Vite rewrites it during development:

text
import { ref } from 'vue'
        ↓ (Vite dev server)
import { ref } from '/node_modules/.vite/deps/vue.js?v=8f2a1c0d'

You can see the same browser behaviour natively with an import map, which is what Vite effectively does for you automatically:

html · try it yourself
<!doctype html>
<html>
  <body style="font-family: system-ui">
    <script type="importmap">
      { "imports": { "greet": "data:text/javascript,export default (n) => 'Hi ' + n + ' from a bare import'" } }
    </script>
    <p id="out">…</p>
    <script type="module">
      import greet from 'greet';
      document.querySelector('#out').textContent = greet('Vite');
    </script>
  </body>
</html>

import.meta

Every module has an import.meta object with information about itself. Browsers provide import.meta.url; Vite adds more:

Property Provided by
import.meta.url Browser / Node: the module's URL
import.meta.env Vite: environment variables and MODE, DEV, PROD
import.meta.hot Vite dev server: the HMR API
import.meta.glob() Vite: import many files by pattern
import.meta.dirname / filename Node 20.11+: handy in vite.config.js

Tip: Avoid CommonJS (require, module.exports) in your source. Vite can consume CommonJS dependencies, but your own code should be ESM.

Test yourself

A module is imported from three different files. How many times does its top-level code run?

  1. Three times
  2. Once
  3. Zero times until called
  4. Once per HMR update only

What does await import('./chart.js') usually become in a Vite production build?

  1. Inlined into the main bundle
  2. A separate lazily-loaded chunk
  3. A CommonJS require
  4. A syntax error

Why can't the browser load import { ref } from 'vue' directly?

  1. Vue is not an ES module
  2. Bare specifiers are not URLs, so the browser cannot resolve them without help
  3. Browsers block all imports
  4. Named imports are not allowed