Modules

ECMAScript 2015 has introduced built-in modules. The features of modules are as follows:

  • Each module is defined in its own file.
  • Functions or variables defined in a module are not visible outside unless you explicitly export them.
  • You can place the export keyword in front of any variable, function, or class declaration to export it from the module.
  • You can use the import keyword to consume the exported variable, function, or class declaration.
  • Modules are singletons. Only a single instance of a module exists, even if it was imported multiple times.

Some exporting possibilities are listed here:

// export data
export let color: string = "red";

// export function
export function sum(num1: number, num2: number) {
return num1 + num1;
}

// export class
export class Rectangle {
constructor(private length: number, private width: number) { }
}

You can declare a variable, function, or class and export it later. You can also use the as keyword to rename exports. A new name is the name used for importing:

class Rectangle {
constructor(private height: number, private width: number) { }
}

export {Rectangle as rect};

Once you have a module with exports, you can access its functionality in another module using the import keyword:

import {sum} from "./lib.js";
import {Rect, Circle} from "./lib.js";

let sum = sum(1, 2);
let rect = new Rect(10, 20);

There is a special case that allows you to import the entire module as a single object. All exported variables, functions, and classes are available on that object as properties:

import * as lib from "./lib.js";

let sum = lib.sum(1, 2);

Imports can be renamed with the as keyword and used under the new name:

import {sum as add} from "./lib.js";

let sum = add(1, 2);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.83.176