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.
// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }
export default function hello(name) { return `Hello, ${name}`; }// 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.
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.
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=hashor?t=timestampto 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.
'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:
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:
<!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?
- Three times
- Once
- Zero times until called
- Once per HMR update only
What does await import('./chart.js') usually become in a Vite production build?
- Inlined into the main bundle
- A separate lazily-loaded chunk
- A CommonJS require
- A syntax error
Why can't the browser load import { ref } from 'vue' directly?
- Vue is not an ES module
- Bare specifiers are not URLs, so the browser cannot resolve them without help
- Browsers block all imports
- Named imports are not allowed