React ES6 Modules


Modules

JavaScript modules allow you to split your code into separate files.

This makes it easy to maintain a code base.

ES modules are based on import and export statements.


Export

You can export a function or vice versa to any file.

Let's create a file with the name person.js, and fill it with the items we want to export.

There are two types of export: Named and Default.


Named Exports

You can create named posts in two ways. In each row, or all at once at the bottom.


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's create another file, named message.js, and use it to show auto export.

You can only have one default post on file.


Example

message.js

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


You can import modules into a two-way file, based on the so-called exports or automated exports.

Named exports should be destroyed using folded brackets. Automatic shipping does not.


Import from named exports

Import named exports from the file person.js:

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

Import from default exports

Import a default export from the file message.js:

import message from "./message.js";