JS: Module
(new in JS: ECMAScript 2015)
xtodoWhat is JS module
- JS modules are JS files designed to be used as a library.
- They differ from normal JS files in several technical ways.
Using keyword export or import implies module
if your JavaScript code uses the keyword
export
or
import
,
then it is considered a module.
you must load it as a module, else it's an error.
except the syntax of dynamic import, like this
import(…)
Loading Module
module must be loaded like this
<script type="module">js_code</script>
<script type="module" src="module_specifier"></script>
Module files are loaded only once, even if you specify it many times.
<script type="module" src="module_specifier"></script> <script type="module" src="module_specifier"></script>
Module files are loaded as deferred by default
Module files are loaded as deferred by default.
Async works for inline file loading of module
when you have
<script async type="module">jscode</script>
the async
works. (not if normal js)
Module specifier
module specifier is the path or url for the module.
either url starting with http
or /
or //
,
or it must start with ./
for relative path.
Loading Module Require HTTP (Cross Origin Error)
- Module file do not work over local file system.
- You get a cross origin error.
You must run the browser over a http server.
Module runs in strict mode
Module runs in strict mode
Module Top-Level Scope is Lexical
normally, when you have
var x = 3;
the x
becomes global property,
e.g. window.x
not so with module. they are local variable within the module file.