How can you share code between JavaScript files?
Topics
JAVASCRIPT
Edit on GitHub
TL;DR
To share code between JavaScript files, you can use modules. In modern JavaScript, you can use ES6 modules with export
and import
statements. For example, you can export a function from one file and import it into another:
// 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 ES6 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
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