在TypeScript中的“import from”和“import require”之间的区别 [英] Difference between `import from` and `import require` in TypeScript

查看:2955
本文介绍了在TypeScript中的“import from”和“import require”之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用node.js,最近我决定给予TypeScript一个镜头,但是我对模块的导入方式感到困惑。我看到两种不同的语法,我找不到它们的区别:

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

这些是一样的吗?如果没有,我应该在哪里使用每一个?

解决方案

import * as a从'a'; 是新的ES6风格导入语法(自Typescript 1.5起可用)。



只要有可能,这个语法应该现在可以使用。



虽然有一个警告。 ES6导入语法只能导入作为模块一部分导出的模块(由ES6定义)或导出的对象(类,接口,vars ...)。



Javascript图书馆将直接导出一个函数或类,相应的定义文件通常如下所示:

 声明模块my-类{

class MyClass {...}

export = MyClass
}

在这种情况下,旧导入语法是唯一可以使用的语法

 code> import MyClass = require(my-class); 

未能使用此语法将导致错误TS2497



查看此问题的详细信息以及可能的解决方法,在以前的情况下,添加定义文件的空模块声明

 声明模块my-class{

class MyClass {...}

模块MyClass {} //< =

export = MyClass
}
/ pre>

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
} 

这篇关于在TypeScript中的“import from”和“import require”之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆