JS Modules

JS Tutorial

JS Version

JS Objects

JS Function

JS Classes

JS Async

JS HTML DOM

JS Browser BOM

JS Web API

JS AJAX

JS JSON

JS vs JQUERY

JS Graphics

JavaScript Modules

Modules

JavaScript modules enable you to break up the code into separate files.

This allows easy maintenance of the code-base.

JavaScript modules depend on the import and export statements.

Export

A function or variable from any file can be exported.

Create a file named person.js, and fill it with the things that need to be exported.

There are two types of exports: Named and Default.

Named Exports

Creating named exports can be done in two ways. In-line individually, 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 us create another file, named message.js, and use it for demonstrating default export.

You can only have one default export in a file.

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 into a file in two ways, depending on if they are named exports or default exports.

Named exports are constructed with the help of curly braces. Default exports are not.

Import from named exports

Import named exports from the file person.js:

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