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:
Alternatively, in Node.js, you can use module.exports
and require
:
Using ES6 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
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: