ES6 Modules

Jure Bajt

  • A group of functions, classes or variables defined in their own file.
  • Things defined in a module are not visible outside unless you explicitly export them.

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();
  • No global scope pollution
  • Source order independence

What makes modules in JS great?

  • Access to npm packages
  • Namespacing you own application code in order to prevent name collisions is not needed anymore
  • Dynamically load modules as required

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 () { ··· });
  • Browserify, Webpack, Rollup, jspm ...

"Time machine" aka build tools, libraries and transpilers

  • Require.js, SystemJS
  • Babel, TypeScript ...
  • JavaScript Package Manager that works on top of SystemJS universal module loader

jspm and SystemJS

  • Out of the box, it works with GitHub and npm
  • SystemJS can import modules at run time in any of the popular formats used today (CommonJS, UMD, AMD, ES6)
  • SystemJS can also transpile code using Babel, TypeScript etc.

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

Thank you!

Made with Slides.com