JavaScript Modules

Modules (Modules)

JavaScript modules allow you to break down code into separate files.

this will make it easier to maintain the codebase. Modules are used import

Modules also depend on the statements from the <script> tag for importing from external files. type="module".

Example

<script type="module">
import message from "./message.js";
</script>

Try it yourself

exports

withfunctionsorvariablesmodules can be stored in any external file.

There are two types of exports:Named ExportsandDefault Exports.

Named Exports

Let's create a file named person.js and fill it with the content we want to export.

You can create named exports in two ways. One is to create them inline one by one, and the other is to create them all at once at the bottom of the file.

Create inline one by one:

person.js

export const name = "Bill";
export const age = 19;

Create all at once at the bottom of the file:

person.js

const name = "Bill";
const age = 19;
export {name, age};

Default Exports

Let's create another file named message.js and use it to demonstrate default export.

Only one default export can be in a file.

Example

message.js

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

Import

You can import modules into a file in two ways, depending on whether they are named exports or default exports.

Named exports are constructed using braces. Default exports are not.

Import from named export

Import named export from file person.js:

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

Try it yourself

Import from default export

Import default export from file message.js:

import message from "./message.js";

Try it yourself

Note

Modules are only applicable to HTTP(s) protocols.

Web pages opened via the file:// protocol cannot use import/export.