Module syntax in javascript

JavaScript Modules

JavaScript modules allow you to break up your code into separate files.

This makes it easier to maintain a code-base.

Modules are imported from external files with the import statement.

Modules also rely on type=»module» in the tag.

Example

Export

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

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

Named Exports

Let us create a file named person.js , and fill it with the things we want to export.

You can create named exports two ways. In-line individually, or all at once at the bottom.

In-line individually:

All at once at the bottom:

const name = «Jesse»;
const age = 40;

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

const message = () => <
const name = «Jesse»;
const age = 40;
return name + ‘ is ‘ + age + ‘years old.’;
>;

Import

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

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

Import from named exports

Import named exports from the file person.js:

Import from default exports

Import a default export from the file message.js:

Note

Modules only work with the HTTP(s) protocol.

A web-page opened via the file:// protocol cannot use import / export.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Install php using composer
Оцените статью