JavaScript Modules


Modules

JavaScript modules help you divide your code into different files.

This simplifies the task of managing a codebase.

You can bring modules from outside files into your code using the import statement.

Modules depend on using type="module" within the <script> tag.


Export

Information like functions or variables can be kept in external files using modules.

There are two kinds of exports: Named Exports and Default Exports.


Named Exports

Create a file called person.js. Put inside it the content you want to share.

You have two ways to make named exports. Either create them individually in-line or make all of them 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

Create a new file called message.js. Use this file to show a default export.

In a file, you're allowed to have only one main thing that gets exported by default.

Example

message.js

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

export default message;

Import

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

Using curly braces creates named exports, while default exports do not use them.

Note

Modules function exclusively with the HTTP(s) protocol.

A webpage opened using the file:// protocol cannot utilize import/export features.