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

Module File Name Extension

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

Loading Module in HTML

Requires attribute type="module"

<script type="module" src="module_specifer"></script>

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

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

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

Loading Module from 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