Loading lesson path
JavaScript modules allow you to break up your code into separate files.
Formula
This makes it easier to maintain the code - base.ES Modules rely on the import and export statements.
You can export a function or variable from any file. Let us create a file named person.js, and fill it with the things we want to export. There are two types of exports: Named and Default.
You can create named exports two ways:
export const name = "Tobias"
export const age = 18All at once at the bottom:
const name = "Tobias"
const age = 18export { name, age }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.
Insert the following code into the newly created file:
const message = () => {
const name = "Tobias";
const age = 18;
return name + ' is ' + age + 'years old.';
};export default message;You can import modules into a file in two ways, based on if they are named exports or default exports. Named exports must be destructured using curly braces. Default exports do not.
Import named exports from the file person.js:
import { name, age } from "./person.js";Import a default export from the file message.js:
import message from "./message.js";