从TypeScript导入CommonJS的最向前兼容的方法是什么? [英] What is the most forwards-compatible way of importing CommonJS from TypeScript?

查看:389
本文介绍了从TypeScript导入CommonJS的最向前兼容的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从TypeScript导入CommonJS模块的以下三种方法中:

Of these three ways of importing a CommonJS module from TypeScript:

  1. import * as foo from "foo
  2. import foo = require("foo")
  3. const foo = require("foo")
  1. import * as foo from "foo
  2. import foo = require("foo")
  3. const foo = require("foo")

哪个与TS和ES模块规范最向前兼容?

Which is most forwards-compatible with both TS and the ES module spec?

也就是说,当/如果"foo"库切换到使用ES模块,以上哪一种最不可能破裂或变得怪异?

That is, when/if the "foo" library switches to using ES modules, which of the above is least likely to break or or become weird?

更新:(1)看起来最好,因为它是真正的ES模块语法,但是我担心要保留我们要导入的CommonJS模块的预期语义.例如,如果预期在导入模块时会产生副作用,则我们希望在使用import * as语法时保留该语义.

另一个更新:我们的目标是ES模块. ES模块使用单独的工具->转变.

Another update: We're targeting ES modules. A separate tool does the ES Module -> transformation.

推荐答案

const foo = require("foo")

这是最糟糕的一个,foo将被键入为任意类型,我将不惜一切代价避免使用它

This one is the worst one, foo will be typed as any, I would avoid it at all cost

import foo = require("foo")

这是打字稿特定的导入语法,应再次避免.在运行时将其编译为var foo = require("foo"),但在编译时将提供类型安全性.这是导入使用导出分配的模块的唯一方法.

This is typescript specific import syntax, and again should be avoided as much as possible. At runtime it is compiled to var foo = require("foo"), but at compile time it offers type safety. It is the only way to import a module that uses export assignment.

import * as foo from "foo"

这是ES2015的官方语法,应尽可能予以支持(我认为导出分配的情况除外,在所有其他情况下都可以使用).

This is the official ES2015 syntax and should be favored whenever possible (except for the export assignment case I think it can be used in all other cases).

如果编译为commonjs,则以上语法在运行时仍将编译为const foo = require("./foo");,因此其行为应相同.

If you compile to commonjs the above syntax will still be transpiled as const foo = require("./foo"); at runtime so it should behave in the same way.

有一个警告,打字稿不会发出未使用的导入和仅用于其类型的导入(请阅读这里),因此,如果要导入具有副作用的模块,可以使用以下语法:

There is one caveat to this, typescript will not emit imports that are unused and import that are only used for their types (read here) so if you want to import a module for side effects you can use this syntax:

import "foo"

这篇关于从TypeScript导入CommonJS的最向前兼容的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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