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.
Alternatively, in Node.js, you can use module.exports and require:
Using ECMAScript modules
Exporting code
To share code, you can use the export keyword to export variables, functions, or classes from a module:
Importing code
You can then import the exported code in another file using the import keyword:
Default exports
You can also export a single default value from a module:
And import it without curly braces:
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:
Importing code
You can then import the exported code using require:
Exporting a single value
You can also export a single value:
And import it directly:
Further reading
- MDN Web Docs on ES6 modules
- Node.js documentation on modules
- Node.js documentation on ECMAScript modules