ES6 Modules
by @arodriguez
An ES6 module is a js file which exports functions, classes or variables.
Everything thats not exported is private for that module and can't be accessed outside it.
var myModule = (function(fromOuterScope) {
// ES6 modules are similar to the module pattern common in ES5 js
return {};
})(someVar);Similar to:
Basic API
// Named export
export const version = '1.0';
// Default export
export default {
appName: 'demo',
baseUrl: 'https://demo-site.com/'
};
// Exporting from another module
export someVar as otherName from './external-setting';
let jsVersion = 'ES6';export
import
import settings from './base/setting';
console.log(settings);
// { appName: 'demo', baseUrl: 'https://demo-site/' }import { version } from './base/setting';
console.log(version); // 1.0import { version as appVersion } from './base/setting';
console.log(appVersion); // 1.0How to use it today
Transpiling and bundlers
Its a two step process. First transpile your ES6 code back to ES5 and into a CommonJS standard. Then bundle your code into a single file to make it browser compatible.
Transpiler
Babel 6
By using presets, it can transform your code into anything you choose. Most commonly used presets are:
- preset-es2015
- preset-stage-0
Bundlers
Browserify
Rollup
CommonJs (node like js) -> Browser
ES6 -> anything
http://rollupjs.org/
http://browserify.org/
How can we benefit from this
Dead code elimination
By using techniques such as tree shaking, each module imported in a page will have only the js it needs and nothing more
This can be achieved because ES6 modules are statically defined, so the bundle can be optimised for size, if a function is never used, its not included.
Dead Scripts Elimination
The dependency tree is defined by the imports on the scripts per page. With that information, its easy to figure out what js files are not being used in the project.
Detecting deprecated js files should be as easy as traversing the dependency tree.
Future Proof
ES6 is the new standard.
It may not be fully implemented in all browsers but with the help of transpilers we can use it today and be ready for the future.
How to use it with django
Compressor module
Custom compressor to transpile and bundle ES6 & modules
https://github.com/kottenator/django-compressor-toolkit
DEMO :)
ES6 Modules
By Alejo Rodriguez
ES6 Modules
- 329