JS: Module
(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-Typeoftext/javascriptfor Apache HTTP Server, you can add the following line to web root dir
.htaccessfile.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
- 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.
Browser developer tools local mode (emulate http server)
Module runs in strict mode
Module runs in Strict Mode