Curriculum
Course: React
Login

Curriculum

React

Text lesson

ES6 Modules

Modules

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.

Export

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

Named exports can be created in two ways: individually in-line or all together at the bottom of the file.

Example

Individually in-line:

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

Create another file named message.js to demonstrate default export. A file can have only one default export.

Example

message.js

const message = () => {
 const name = "Jesse";
 const age = 40;
 return name + ' is ' + age + 'years old.';
};

export default message;

Import

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.

Example

Import named exports from the person.js file:

import { name, age } from "./person.js";

Example

Import the default export from the message.js file:

import message from "./message.js";