Javascript Modules
Refs
What is a Javascript Module ?
Just a javascript file which can import functionality from other and export its own functionality.
Why do we need Javascript Module ?
Javascript starts small, but now it grows very large and complex.
Split large javascript into separate modules and re-use it.
Module Types
CommonJS
Intro
- The module specification invented by node.js.
- Only used in server environment.
Syntax
For module:
1 | // export: |
Problem
CommonJS is synchronous.
Not a problem for server environment, as it loads modules at startup.
For browser environment, browser has to wait for a long time, that will make browser ‘dead’, it stops responding.
AMD
Intro
- Asynchronous Module Definition.
- Introduced by
requireJS
. - All code is wrapped up in a callback, the callback runs after module loading is complete.
Syntax
1 | // config: |
CMD
Intro
- Common Module Definition.
- Introduced by ‘sea.js’
- Asynchronous.
Syntax
1 | // define |
ES6 Module
Intro
- Official.
- Automatically uses strict mode. (i.e.
use strict
) - Supported natively in modern browsers.(i.e. IE excluded)
Syntax
1 | // import and export |
Browser native support:
1 | <script type="module" src='main.js'></script> |
Same as normal script import, only difference is type="module"
.
Features
- Deferred by default, which makes ES6 modules asynchronous.
- Executed only once, even referenced in multiple tags.
- Supports dynamic loading, loads module on demand:
1
2
3
4import('./modules/myModule.js')
.then((module) => {
// Do something with the module.
});
FAQ
Javascript Modules