Jure Bajt
What is a module?
Multiple named exports
//------ math.js ------
export function add (a, b) {
return a + b;
}
export function subtract (a, b) {
return a - b;
}
//------ main.js ------
import { add, subtract } from 'math';
console.log(add(1, 2)); // 3
console.log(subtract(4, 3)); // 1
Single default export
//------ foo.js ------
export default function () { ··· }
//------ main.js ------
import foo from 'foo';
foo();
What makes modules in JS great?
The past
//------ jquery.js ------
window.$ = function () { ··· };
//------ index.html ------
<script src="jquery.js"></script>
<script>
$(function () { ··· });
</script>
The present
It's a mess ...
CommonJS
AMD
UMD
ES6 Modules
window.myModule = function () { ··· };
The future
//------ jquery.js ------
export default function $ () { ··· };
//------ main.js ------
import $ from 'jquery';
$(function () { ··· });
"Time machine" aka build tools, libraries and transpilers
jspm and SystemJS
Demo
npm install -g jspm
mkdir demo_project && cd demo_project
npm init -y
npm install jspm --save-dev
jspm init
jspm bundle js/main.js bundle.js
//------ index.html ------
<script src="jspm_packages/system.js"></script>
<script src="config.js"></script>
<script src="bundle.js"></script>
<script>
System.import('js/main.js');
</script>
Resources