简体   繁体   中英

Angular2 importing syntax: “import * as <foo>” vs “import {<foo>}”

Im seeing two different way modules can be imported.

Most import look like 'import {<something>} (ie import { Component } from '@angular/core'; )

The others import like 'import * as <something> (ie import * as _ from "lodash"; )

From what I understand you import using the latter method when importing vanilla js modules into your project using typings (ie typings install lodash=npm --save ) and not for Angular2 modules, is that correct?

If my assumption is correct, are you using both imported classes/modules the same way ( ie when your declare them to use inside a Components class)?

Using import as something works like an alias in that module,helpful when there are two or more imported components with same name,not using alias, the later component will override the first.

There can be multiple named exports:

//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}

//------ main.js ------
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
You can also import the complete module:

//------ main.js ------
import * as lib from 'lib';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM