JS: Module

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

What is javascript module

JS modules are JavaScript files designed to be used as a reusable JavaScript code groups, with clean system to import export of names of variable function or object, without polluting global namespace.

How is a module file different from normal javascript file

A module file typically contains export statement, or import statement, else it is useless as a module.

However, technically, any JavaScript file can be loaded as a module.

🛑 warning: module is defined by how it is loaded

in JavaScript, whether a JavaScript file is a module is determined by how the runtime loads it, and the runtime determines how to load it by load declarations.

For example, browser loads a JavaScript file as module if the script tag has attribute type="module", e.g.

<script type="module" src="./math.js"></script>

File with export or import must be loaded as module

if you have a JavaScript file that contains export statement or import statement, it must be loaded as module, else its error.

Module files top-level names are local

When a file is loaded as module, its top-level names (variable or function) are local to the file.

Module example

Module file name extension

.js

Standard File Name Extension for both JavaScript Module file and plain JavaScript file.

.mjs

Non-standard File Name Extension for JS module files used by node.js community.

🛑 warning: if you use .mjs, make sure your HTTP server is configured for files with mjs filename extension to be Content-Type of text/javascript

for Apache HTTP Server, you can add the following line to web root dir .htaccess file.

AddType text/javascript .mjs

Load js as module in html

add this attibute in script tag type="module"

Js file

<script type="module" src="./geom.js"></script>

The value to the src attribute is called Module Specifer. It is a URL, path, or name, with some restrictions.

Js code

<script type="module">
import { something } from './math.js';
console.log(something);
</script>

Defer vs async

<script async type="module">/* code */</script>

Load module in js code

Loading module require http (cross origin error)

run a local http server, see Python: Start Python HTTP Server

Module runs in strict mode

Module runs in Strict Mode