Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

node.js - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...