How can you share code between JavaScript files?
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.jsexport function greet() {console.log('Hello, world!');}// file2.jsimport { greet } from './file1.js';greet();
Alternatively, in Node.js, you can use module.exports and require:
// file1.jsmodule.exports = function greet() {console.log('Hello, world!');};// file2.jsconst 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.jsexport 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.jsimport { add, PI } from './utils.js';console.log(add(2, 3)); // 5console.log(PI); // 3.14
Default exports
You can also export a single default value from a module:
// math.jsexport default function subtract(a, b) {return a - b;}
And import it without curly braces:
// main.jsimport 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.jsmodule.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.jsconst utils = require('./utils.js');console.log(utils.add(2, 3)); // 5console.log(utils.PI); // 3.14
Exporting a single value
You can also export a single value:
// math.jsmodule.exports = function subtract(a, b) {return a - b;};
And import it directly:
// main.jsconst subtract = require('./math.js');console.log(subtract(5, 2)); // 3
Further reading
- MDN Web Docs on ES6 modules
- Node.js documentation on modules
- Node.js documentation on ECMAScript modules