JavaScript modules enable you to split your code into separate files, making it easier to maintain the codebase.
Modules are imported from external files using the import statement.
They also require the type=”module” attribute in the <script> tag.
<script type=”module”> import message from “./message.js”; </script> |
Modules containing functions or variables can be stored in any external file.
There are two types of exports: Named Exports and Default Exports.
Let’s create a file called person.js and include the items we want to export.
You can create named exports in two ways: either inline, individually, or all together at the bottom of the file.
person.js
export const name = “Jesse”; export const age = 40; |
person.js
const name = “Jesse”; const age = 40; export {name, age}; |
Let’s create another file called message.js to demonstrate default export.
A file can only have one default export.
message.js
const message = () => { const name = “Jesse”; const age = 40; return name + ‘ is ‘ + age + ‘years old.’; }; export default message; |