JavaScript modules enable you to split your code into separate files, improving maintainability.
ES modules use import
and export
statements for managing code between files.
You can export functions or variables from any file.
In the file person.js, we’ll define the exports, which can be either Named or Default.
Named exports can be created in two ways: individually in-line or all together at the bottom of the file.
Individually in-line:
person.js
export
|
person.js
const |
Create another file named message.js to demonstrate default export. A file can have only one default export.
message.js
const |
Modules can be imported in two ways, depending on whether they are named or default exports. Named exports require destructuring with curly braces, while default exports do not.
Import named exports from the person.js
file:
import |
Import the default export from the message.js file:
import |