Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Modules

Modules

JavaScript modules enable you to split your code into separate files, making it easier to maintain the codebase.

Modules are imported from external files using the import statement.

They also require the type=”module” attribute in the <script> tag.

Example

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

Export

Modules containing functions or variables can be stored in any external file.

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

Named Exports

Let’s create a file called person.js and include the items we want to export.

You can create named exports in two ways: either inline, individually, or all together at the bottom of the file.

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 called message.js to demonstrate default export.

A file can only have one default export.

Example

message.js

const message = () => {
const name = “Jesse”;
const age = 40;
return name + ‘ is ‘ + age + ‘years old.’;
};

export default message;