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 units, 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.

Module is determined 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

Loading module in html

Load a module file

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

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

Load js source code as module

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

defer vs async load

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

Loading module in javascript code

Loading module require http (cross origin error)

Browser developer tools local mode (emulate http server)

Module runs in strict mode

Module runs in Strict Mode