Chapter 15 Cheatsheet: Modules

This cheatsheet summarizes the mechanics of JavaScript modules covered in Chapter 15.

Why Modules?

Modules allow you to organize your code across multiple files, making large codebases maintainable. Each file is treated as an isolated module.

The Legacy Standard: CommonJS

CommonJS was built for Node.js. It requires files synchronously and uses a specific object for exporting.

// Exporting
module.exports = { myFunction };

// Importing
const { myFunction } = require('./myFile.js');

The Modern Standard: ES6 Modules

ESM is the official ECMAScript standard used in modern browsers and modern Node.js applications.

// Named Export
export const myFunc = () => {};
import { myFunc } from './myFile.js';

// Default Export
export default myFunc;
import myCustomName from './myFile.js';

Enabling ES6 Modules

  • In Node.js: Add "type": "module" to your package.json.
  • In the Browser: Add type="module" to your script tag (<script type="module" src="app.js"></script>).

Strict Mode

Adding "use strict"; to the top of a file forces the JS engine to be less forgiving, catching silent errors and preventing accidental global variables. Note: Modern ES6 modules run in Strict Mode automatically.

Bundlers (e.g., Vite, Webpack)

Tools used during the build step to crawl your module imports and package your code into highly optimized, minified files suitable for fast delivery over the internet.