JSJavaScript
AdvancedLesson 16 of 16

Modules, npm & Tooling – JavaScript

ES modules, package.json, bundlers and quality tools.

You split larger programs into ES modules. With export you make something visible to the outside, with import you use it in another file. (These examples need multiple files and therefore do not run in this site's browser editor.)

// mathe.js
export const PI2 = Math.PI * 2;
export function quadrat(x) {
  return x * x;
}
export default class Rechner {
  add(a, b) { return a + b; }
}

// main.js
import Rechner, { quadrat, PI2 as ZWEI_PI } from "./mathe.js";
import * as mathe from "./mathe.js";
console.log(new Rechner().add(1, 2), quadrat(4), mathe.PI2 === ZWEI_PI);

In the browser you include modules with type="module", in Node.js via "type": "module" in the package.json (or the file extension .mjs). Older projects still use CommonJS (require/module.exports). With import() you load code only when needed:

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

// Lazy loading – loads the module only on the first call:
async function zeigeDiagramm() {
  const { zeichne } = await import("./diagramm.js");
  zeichne();
}

npm manages dependencies. The package.json describes your project, and package-lock.json freezes exact versions:

npm init -y
npm install dayjs             # runtime dependency
npm install -D vitest eslint  # for development only
npm run test                  # script from package.json
npx prettier --write .        # run a package without installing it

A typical toolbox: Vite (dev server and bundler), ESLint (finds errors and style problems), Prettier (consistent formatting), Vitest or the built-in node:test (tests). Node.js also ships modules like node:fs, node:path and node:http:

// tests/mathe.test.js  (run with: node --test)
import { test } from "node:test";
import assert from "node:assert/strict";
import { quadrat } from "../mathe.js";

test("quadrat", () => {
  assert.equal(quadrat(3), 9);
});
WarningEvery installed package is third-party code with its own dependencies (supply-chain risk). Vet packages before installing them, run npm audit regularly and keep the lock file in the repository.