官术网_书友最值得收藏!

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);
主站蜘蛛池模板: 佳木斯市| 巴塘县| 桂阳县| 泰安市| 古蔺县| 大名县| 永安市| 宜阳县| 凤凰县| 宜州市| 柳江县| 襄樊市| 隆安县| 汕头市| 许昌市| 社旗县| 江源县| 林州市| 缙云县| 阳高县| 古浪县| 三江| 黄龙县| 孝昌县| 积石山| 平昌县| 安庆市| 永靖县| 木兰县| 金阳县| 桓仁| 孝感市| 柞水县| 定日县| 淮南市| 县级市| 万载县| 石泉县| 察哈| 鄂伦春自治旗| 高雄县|