Saturday, January 2, 2016

ES6 Modules

Exporting and Importing

"export" keyword is used to expose parts of the code to other modules.
You can place "export" keyword in front of any variable, function or class to export it from the module.

// export data
export var color = 'red';
export let name = 'deepak';
export const magicNumber = 7;
// export function
export function sum(num1, num2) {
return num1 + num2;
}
// export class
export class Rectangle {
constructor(length, width) {
this.length = length;
this.width = width;
}
}
view raw export.js hosted with ❤ by GitHub
Once you have module with exports, you can access the functionality in another module by using the "import" keyword.

import { sum } from 'example';
console.log(sum(1, 2)); // 3
view raw import.js hosted with ❤ by GitHub
The above example import only "sum" from the example module.
If you want to import multiple identifiers from the example module, you can explicitly list them out.

import { sum, name, magicNumber } from 'example';
console.log(name); // 'deepak'
console.log(sum(1, 2)); // 3
console.log(sum(1, magicNumber)); // 8
view raw import.js hosted with ❤ by GitHub
You can also import the entire module as a single object. All of the exports are then available on that object as properties.

import * as example from 'example';
console.log(example.sum(1, 2)); // 3
console.log(example.name); // 'deepak'
console.log(example.magicNumber); // 7
view raw import.js hosted with ❤ by GitHub

Exporting and Importing defaults

The default value for a module is a single variable, function or class as specified by the "default" keyword.

export default function(num1, num2) {
return num1 + num2;
}
This module exports a function as the default. The "default" keyword indicates that this is a default export and the function does't require a name because the module itself represent the function.

You can import a default value using the following syntax.

import sum from 'example';
console.log(sum(1, 2)); // 3
For modules that export both a default and one or more non-defaults. For instance suppose you have this module.

export let name = 'deepak';
export default function(num1, num2) {
return num1 + num2;
}
You can then import both "name" and the default function using the following.

import sum, { name } form 'example';
// import { default as sum, name } from 'example';
console.log(name); // 'deepak'
console.log(sum(1, 2)); // 3
Resource
https://leanpub.com/understandinges6/read#leanpub-auto-modules

No comments:

Post a Comment