HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Modules

JavaScript modules allow you to break up your code into separate files. This makes it easier to maintain a code-base. Modules rely on two main keywords: export and import.


1. Exporting

You can export variables or functions from any file. There are two types of exports: Named and Default.

Named Exports

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

// person.js
export const name = "Mim";
export const age = 22;

// OR
const name = "Mim";
const age = 22;
export { name, age }; 

Default Exports

You can only have one default export in a file.

// message.js
const message = () => {
  return "Hello World!";
};
export default message;

2. Importing

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

Import Named Exports

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

Import Default Exports

import message from "./message.js";

Script Tag Requirement

To use modules in an HTML file, the <script> tag must have the type="module" attribute.

<script type="module" src="main.js"></script>
Security Note: Modules only work via the HTTP(S) protocol. A page opened via the file:// protocol (double-clicking a local HTML file) cannot load modules. You must use a local server!

Key Points to Remember

  • Modules keep code organized, reusable, and maintainable
  • Use export to make code available to others
  • Use import to bring in external code
  • Named exports require curly braces { } when importing
  • Default exports don't require curly braces and can be renamed during import
  • Modules always run in Strict Mode automatically
  • They provide a private namespace, preventing variable collisions