Quiz

How can you share code between JavaScript files?

Topics
JavaScript

TL;DR

Share code through modules with an explicit public API. ECMAScript modules (export / import) are the language standard and work in browsers, Node.js, and toolchains with host-specific resolution rules. CommonJS (module.exports / require) remains relevant to existing Node.js code and packages; do not mix the two formats without checking the runtime's interoperability rules.

// file1.js
export function greet() {
console.log('Hello, world!');
}
// file2.js
import { greet } from './file1.js';
greet();

Alternatively, in Node.js, you can use module.exports and require:

// file1.js
module.exports = function greet() {
console.log('Hello, world!');
};
// file2.js
const greet = require('./file1.js');
greet();

Using ECMAScript modules

Exporting code

To share code, you can use the export keyword to export variables, functions, or classes from a module:

// utils.js
export function add(a, b) {
return a + b;
}
export const PI = 3.14;

Importing code

You can then import the exported code in another file using the import keyword:

// main.js
import { add, PI } from './utils.js';
console.log(add(2, 3)); // 5
console.log(PI); // 3.14

Default exports

You can also export a single default value from a module:

// math.js
export default function subtract(a, b) {
return a - b;
}

And import it without curly braces:

// main.js
import subtract from './math.js';
console.log(subtract(5, 2)); // 3

Using CommonJS modules in Node.js

Node.js supports both ESM and CommonJS. The file extension, nearest package.json type field, and package configuration determine how a file is interpreted. The following is the CommonJS form:

Exporting code

In Node.js, you can use module.exports to export code:

// utils.js
module.exports.add = function (a, b) {
return a + b;
};
module.exports.PI = 3.14;

Importing code

You can then import the exported code using require:

// main.js
const utils = require('./utils.js');
console.log(utils.add(2, 3)); // 5
console.log(utils.PI); // 3.14

Exporting a single value

You can also export a single value:

// math.js
module.exports = function subtract(a, b) {
return a - b;
};

And import it directly:

// main.js
const subtract = require('./math.js');
console.log(subtract(5, 2)); // 3

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise
Check your understanding Exercise

A browser application needs to share a formatPrice function without adding globals. Which approach uses the standard JavaScript module boundary?