JavaScript Modules
What is Modules
JavaScript modules allow you to break up your code into separate files. This makes it easier to maintain the code-base.
JavaScript modules rely on the import and export statements.
Export
You can export a function or variable from any file.
There are two types of exports: Named and Default.
- Named Exports
- In-line individually
- all at once at the bottom
- Default Exports
Let us create a file named person.js, and fill it with the things we want to export.
In-line individually:
person.js
export const name = "Jesse"; export const age = 40;
All at once at the bottom:
person.js
const name = "Jesse"; const age = 40; export {name, age};
Default Exports
Let us create another file, named message.js, and use it for demonstrating default export.
You can only have one default export in a file.
message.js
const message = () { const name = "Jesse"; const age = 40; return name + 'is' + age + ' years old ' ; }; export default message;