打字稿中的import x = require('x')`和`const x = require('x')`之间的区别 [英] Difference between `import x = require('x')` and `const x = require('x')` in typescript
问题描述
在es6中,似乎 import x = require('x')
是无效的语法,并且打字稿文档中没有明确的解释.
It seems import x = require('x')
is an invalid syntax in es6, and there is no clear explanation in typescript documentation.
推荐答案
Q1: import…= require(...)
与 const…= require(...)
在运行时(或一旦编译了代码),两种语法之间没有区别,第一种语法转换为第二种语法.
Q1: import … = require(…)
versus const … = require(…)
At runtime (or once the code is compiled), there is no difference between the two syntaxes, the first one is converted to the second one.
import x = require('x')
此语法特定于TypeScript.常量 x
的类型由在导入的程序包或程序包 @ types/x
中定义的某些类型给出.
This syntax is specific to TypeScript. The constant x
is of type given by some typing defined in the imported package or in a package @types/x
.
const x = require('x')
这是JavaScript(当然还有TypeScript)中的有效语法.在TypeScript中,常量 x
的类型为 any
.
This is a valid syntax in JavaScript and of course in TypeScript. In TypeScript, the constant x
is of type any
.
从'x'导入x
和import x = require('x')
import…from ...
的语法来自ES6标准.我建议阅读此介绍关于ES6模块以及如何导入和导出它们.
The syntax import … from …
is from the ES6 standard. I suggest to read this introduction to ES6 modules and how to import and export them.
但是,简而言之,语法从'x'导入x
等效于:
But, in short, the syntax import x from 'x'
is equivalent to:
import x = require('x').default
(请注意 .default
成员.)
(Notice the .default
member.)
ES6标准规定可以将所有导出的成员导入单个命名空间对象模块" .
The ES6 standard states that all exported members can be imported into a single "namespace object module".
然后 import x = require('x')
的最接近标准语法是:
Then the closest standard syntax of import x = require('x')
is:
import * as x from 'x'
该语法当前可用于TypeScript转译,因为代码已转换为 const…= require(...)
.
This syntax currently works well with the TypeScript transpilation because the code is converted to a const … = require(…)
.
但是:该语法仅在标准定义的上下文中使用.因为,当您的代码将使用ES6模块的本机版本时,您将无法以这种方式导入函数或类.
However: This syntax should be used only in the context defined by the standard. Because, when your code will use a native version of ES6 modules, you won't be able to import a function or a class that way.
这篇关于打字稿中的import x = require('x')`和`const x = require('x')`之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!