JS: Module
(new in JS: ECMAScript 2015)
What is JavaScript Module
- JS modules are JS files designed to be used as a library.
- Any JS file that imports module, is also a module.
How is JavaScript Module File Differ from Normal JavaScript File
- Module files contain
exportorimportsstatement. - Module files's top-level names (variable or function) are local to the file.
- Loading module file in HTML requires attribute
type="module"inscripttag, and must be over HTTP server. (local files won't work).
🛑 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-Typeoftext/javascriptfor Apache HTTP Server, you can add the following line to web root dir
.htaccessfile.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
- Module files are loaded as
deferby default. - Attribute
asynccan be used. It overrides the defaultdeferbehavior.
<script async type="module">/* code */</script>
- Module files are loaded only once, even if you specify it many times.
Loading Module in JavaScript Code
Loading Module Require HTTP (Cross Origin Error)
- Module file does not work over local file system. (You get a cross origin error.)
- Module must be loaded over HTTP server.
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