Modules in JavaScript
Modules is necessary to isolate one part of program from another.
Module Pattern
This is an old school way to do it. It’s based on the ideas of global scope and function scopes. IIFE:
var fightModule = (function () {
var harry = '...';
var voldemor = '...';
function fight() {
console.log(harry, voldemor);
}
return {
fight: fight,
};
})();
fightModule.fight();
This function should return all public variables and functions. jQuery is an example.
Pros:
- We reveal only one variable (name of module,
fightModule
in example above), and hihe everything else
Cons:
- We still polluting to the global namespace
- We have to be sure that order of
<script>
tags is correct.
CommonJS and AMD
AMD - asyncronous module definition
CommonJS:
Definition:
function fight() {
// ...
}
module.exports = {
fight: fight
}
Usage:
var module1 = require('module1');
var module2 = require('module2');
CommonJS is created mainly for the server (Node.js). It’s used by NPM also. In Node.js it works synctonously.
ES6 Modules
import module1 from 'module1';
import module2 from 'module2';
export function jump() {
// ...
}
<script type="module" src="./script.js">
If we use export default
we can import it without {}