JS Modules

Modules help organize code into reusable files. Learn how to export and import functionality in modern JavaScript.

On this page

Modules Intro

JavaScript modules let you split code into multiple files and import/export what you need. Modules run in strict mode by default and have their own scope.

In the browser, use modules with <script type="module">.

<script type="module" src="app.js"></script>

In modules, top-level variables are not global:

// app.js (module)
const version = "1.0";
console.log(version);

Modules Export

Use export to expose values from a module.

Named exports:

// math.js
export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}

export function multiply(a, b) {
  return a * b;
}

Default export (one per file):

// user.js
export default function createUser(name) {
  return { name };
}

You can also export later:

// config.js
const apiUrl = "/api";
const timeout = 5000;

export { apiUrl, timeout };

Modules Import

Use import to bring exported values into another module.

Import named exports:

// app.js
import { PI, add } from "./math.js";

console.log(PI);
console.log(add(2, 3));

Import a default export:

import createUser from "./user.js";

const u = createUser("Ozan");
console.log(u);

Import everything (namespace import):

import * as MathLib from "./math.js";

console.log(MathLib.PI);
console.log(MathLib.multiply(3, 4));

Rename imports to avoid name conflicts:

import { add as sum } from "./math.js";
console.log(sum(5, 6));

Modules Namespace

A namespace import collects all named exports under one object. This is useful for organization and avoiding many individual imports.

import * as Utils from "./utils.js";

// Utils.formatDate(...)
// Utils.slugify(...)

Note: The namespace object is read-only for exports (you cannot reassign exported bindings from outside).

Modules Dynamic

Dynamic imports load modules on demand. They return a Promise and are useful for code-splitting or conditional loading.

async function loadFeature() {
  const module = await import("./feature.js");
  module.run();
}

loadFeature();

Conditional dynamic import:

async function maybeLoad(isAdmin) {
  if (!isAdmin) return;

  const admin = await import("./admin.js");
  admin.showAdminPanel();
}

Practical Notes

  • Modules use strict mode by default.
  • In browsers, modules require correct file paths and a server environment (not file://).
  • Use defer behavior: module scripts are deferred automatically.

Next Step

Continue with JS Meta & Proxy or JS Asynchronous patterns depending on your learning path.

JS Modules Examples (8)