TExcelTAD
Home › JavaScript › JS Modules

JavaScript Modules

As programs grow, keeping everything in one file becomes unmanageable. Modules let you split code into separate files, each with its own scope. A module decides what to share with export, and other modules pull in what they need with import. ES modules (ESM) are the standard module system for both browsers and Node.js.

Exporting

There are two kinds of exports. A module can have many named exports and at most one default export:

js
// math.js
export const PI = 3.14159;

export function circleArea(r) {
  return PI * r * r;
}

function secretHelper() {}       // not exported: private to this file

export default function square(x) {
  return x * x;
}

You can also export a list at the end of the file, optionally renaming:

js
const VERSION = "1.2.0";
function format(n) { return n.toFixed(2); }
export { VERSION, format as formatNumber };

Importing

js
// main.js
import square, { PI, circleArea } from "./math.js";   // default + named
import { formatNumber as fmt } from "./utils.js";      // rename on import
import * as math from "./math.js";                    // everything as an object

console.log(square(4), circleArea(1), math.PI);
Syntax Imports
import x from "./m.js" the default export, under any name you choose
import { a, b } from "./m.js" named exports, by their exact names
import { a as alias } from "./m.js" a named export, renamed
import * as m from "./m.js" all exports as a namespace object
import "./m.js" just run the module (side effects)
await import("./m.js") load dynamically, at runtime

Trying it in a playground

A playground is a single file, but we can still try real import syntax. A data: URL can hold a whole module's source code, and dynamic import() loads it just as it would load a file:

js · try it yourself
const source = `
  export const PI = 3.14159;
  export function circleArea(r) { return PI * r * r; }
  export default function square(x) { return x * x; }
`;
const url = "data:text/javascript," + encodeURIComponent(source);

const mod = await import(url);
console.log(Object.keys(mod).sort());
console.log(mod.default(5));
console.log(mod.circleArea(2).toFixed(2));

const { PI, default: sq } = mod;    // destructure the namespace
console.log(PI, sq(3));
[ 'PI', 'circleArea', 'default' ]
25
12.57
3.14159 9

Notice the namespace object: named exports appear under their names, and the default export under the key default.

Modules have their own scope

Top-level variables in a module are not global — they're private to that module unless exported. Each module is also evaluated only once, no matter how many times it's imported, so all importers share the same instance:

js · try it yourself
const counterSource = `
  let count = 0;
  export function next() { return ++count; }
`;
const url = "data:text/javascript," + encodeURIComponent(counterSource);

const first = await import(url);
const second = await import(url);       // same URL -> same module instance
first.next();
first.next();
console.log(second.next());
console.log(first === second);
console.log(typeof count);              // module variables stay private
3
true
undefined

Modules in the browser

Load a module with type="module". Module scripts are deferred automatically, always in strict mode, and can use top-level await:

html
<script type="module" src="./main.js"></script>

<script type="module">
  import { circleArea } from "./math.js";
  document.body.textContent = circleArea(2);
</script>

Things to know:

  • Import paths in browsers need the file extension (./math.js) or a full URL; bare names like "lodash" need an import map or a bundler.
  • Modules must be served over HTTP(S). Opening index.html directly from disk (file://) blocks them — use a dev server such as Vite.
  • In Node.js, use the .mjs extension or "type": "module" in package.json.

Dynamic import

import() returns a promise, so you can load code only when it's needed — for example, a heavy chart library when the user opens the statistics page:

js
button.addEventListener("click", async () => {
  const { drawChart } = await import("./charts.js");
  drawChart(data);
});

Bundlers like Vite automatically split dynamically imported modules into separate files.

Tip: Prefer named exports in most code: they're easier to search for, auto-import in editors works better, and renaming is explicit. Use a default export when a module clearly has one main thing (a class or a component).

Test yourself

How many default exports can a module have?

  1. None
  2. At most one
  3. Exactly two
  4. Unlimited

Which statement imports the named export sum from ./calc.js?

  1. import sum from "./calc.js"
  2. import { sum } from "./calc.js"
  3. require("./calc.js").sum
  4. import * from "./calc.js"

What does import() (dynamic import) return?

  1. The module object directly
  2. A promise of the module namespace
  3. A string
  4. undefined