JS: Module

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2015)

What is JavaScript Module

How is JavaScript Module File Differ from Normal JavaScript File

🛑 WARNING: Any JavaScript code (or file) containing import statement is also treated as module.

Module Example

Module File Name Extension

.mjs
File Name Extension for JS module files, used in node.js community. (non-standard)

🛑 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
.js
File Name Extension for JS file including module files. (standard)

Loading Module in HTML

Requires attribute type="module"

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

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

🛑 WARNING: Any JavaScript file containing the import statement is also treated as a module, therefore must be loaded as module.

JavaScript Module code can be loaded as embeded code directly (i.e. no file.):

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

example

<script type="module">
// file name: lib.js
const f1 = ((x) => (x + 1));
const f2 = ((x) => (x + 2));
export { f1, f2 };
</script>

example

<script type="module">
// loading a module
import { f1, f2 } from "./lib.js";
// do something
</script>

defer vs async Load

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

Loading Module in JavaScript Code

Loading Module Require HTTP (Cross Origin Error)

Module runs in strict mode

Module runs in Strict Mode

Module Top-Level Name's Scope Are the Module File

For module files, top-level names (variable or function) have scope limited to the file. This is different from non-module JavaScript files, where top-level names have global scope, in fact they become properties of the the Global Object

JavaScript. Module Import Export