TypeScriptImporting external libraries


Syntax

  • import {component} from 'libName'; // Will import the class "component"
  • import {component as c} from 'libName'; // Will import the class "component" into a "c" object
  • import component from 'libname'; // Will import the default export from libName
  • import * as lib from 'libName'; // Will import everything from libName into a "lib" object
  • import lib = require('libName'); // Will import everything from libName into a "lib" object
  • const lib: any = require('libName'); // Will import everything from libName into a "lib" object
  • import 'libName'; // Will import libName module for its side effects only

Remarks

It might seem that the syntax

import * as lib from 'libName';

and

import lib = require('libName');

are the same thing, but they are not!

Let us consider that we want to import a class Person exported with TypeScript-specific export = syntax :

class Person {
...
}
export = Person;

In this case it is not possible to import it with es6 syntax (we would get an error at compile time), TypeScript-specific import = syntax must be used.

import * as Person from 'Person';  //compile error
import Person = require('Person');  //OK

The converse is true: classic modules can be imported with the second syntax, so, in a way, the last syntax is more powerful since it is able to import all exports.

For more information see the official documentation.