美文网首页
typescript import x = require('x

typescript import x = require('x

作者: peerben | 来源:发表于2019-03-01 13:22 被阅读0次

https://stackoverflow.com/questions/52534910/difference-between-import-x-requirex-and-const-x-requirex-in-typ

简直解释的不要再清楚

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.

With import:

import x = require('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.

With const:

const x = require('x')

This is a valid syntax in JavaScript and of course in TypeScript. In TypeScript, the constant x is of type any.

Q2: import … from … versus import … = require(…)

How about difference between import x from 'x' and import x = require('x')

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.

But, in short, the syntax import x from 'x' is equivalent to:

import x = require('x').default

(Notice the .default member.)

How to convert import … = require(…) to the ES6 syntax

The ES6 standard states that all exported members can be imported into a single "namespace object module".

Then the closest standard syntax of import x = require('x') is:

import * as x from 'x'

This syntax currently works well with the TypeScript transpilation because the code is converted to a const … = require(…).

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.

相关文章

网友评论

      本文标题:typescript import x = require('x

      本文链接:https://www.haomeiwen.com/subject/vqlduqtx.html