Home » Nodejs » Difference between `import from` and `import require` in TypeScript

Difference between `import from` and `import require` in TypeScript

Posted by: admin November 30, 2017 Leave a comment

Questions:

I use node.js and I recently decided to give TypeScript a shot, But I’m kinda confused on how modules get imported. I see two different syntax that I couldn’t find out what’s their difference exactly:

import * as a from 'a'; // ES6 standard to import stuff
// OR ...
import a = require('a');

Are these the same thing? and if they’re not, where should I use each one of them?

Answers:

import * as a from 'a'; is the new “ES6 style” import syntax (available since Typescript 1.5).

Whenever possible, this syntax should now be used.

There is one caveat though. The ES6 import syntax can only import modules (as defined by ES6) or objects (classes, interfaces, vars,… ) exported as part of a module.

Some Javascript librairies will directly export a function or class, and the corresponding definition file will typically look like this:

declare module "my-class" {

    class MyClass { ... }

    export = MyClass
} 

In this case, the “old” import syntax is the only one that can be used

import MyClass = require("my-class");

Failure to use this syntax will result in error TS2497

Check this issue for details and a possible workaround which would be, in the previous case, to add an empty module declaration to the definition file

declare module "my-class" {

    class MyClass { ... }

    module MyClass {} // <=

    export = MyClass
}