Vyga Vyga - 2 years ago 193
Javascript Question

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

Im seeing two different way modules can be imported.

Most import look like

'import {<something>}

import { Component } from '@angular/core';

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

From what I understand you import using the latter method when importing vanilla js modules into your project using typings (i.e.
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)?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download