简体   繁体   中英

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

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?

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
} 

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