Tech Interview RoomStudy guides

JavaScript

What are ES modules? Compare them with CommonJS, and explain tree shaking.

Intermediate · 2 min read · Lesson 10 of 12 in JavaScript

ES modules (ESM)

  • import / export, the standard module system in browsers and Node.js.
  • Static: imports are at the top level and resolved before code runs, so tools can analyse them.
  • Live bindings: an imported variable reflects later changes in the exporting module.
  • Always strict mode; top-level await is allowed; loaded asynchronously in browsers (<script type="module"> is deferred by default).
  • import() is the dynamic form, returning a promise; bundlers turn it into a separate chunk (code splitting).

CommonJS (CJS)

  • require() / module.exports, the original Node.js system.
  • Dynamic and synchronous: require can be called anywhere, with computed paths.
  • Exports are a copy of the value at the time of the require.

Tree shaking

Because ESM imports are static, bundlers (Vite with Rollup, webpack, esbuild) can see which exports are actually used and drop the rest. It needs: ESM syntax, code without side effects at import time, and ideally "sideEffects": false in the library's package.json. import * as _ from 'lodash' from a CJS build cannot be shaken; import { debounce } from 'lodash-es' can.

Example

js
// math.js
export let calls = 0;
export function add(a, b) { calls++; return a + b; }
export function unused() { /* removed by tree shaking if nobody imports it */ }

// app.js
import { add, calls } from './math.js';
add(1, 2);
console.log(calls);           // 1: live binding

// lazy-load a heavy chart only when needed
button.addEventListener('click', async () => {
  const { renderChart } = await import('./chart.js');
  renderChart();
});

Follow-up questions interviewers ask

Try answering each one before you open it.

What is a barrel file and why can it hurt performance?

An index.ts that re-exports everything from a folder. Importing one item can make the bundler and the dev server load the whole folder, slowing builds and tests, and can defeat tree shaking when any module has side effects. Import from the specific file in large codebases, or make sure the package is marked side-effect free.