用于导入 commonjs / amd 模块的新 es6 语法,即 `import foo = require('foo')`

New es6 syntax for importing commonjs / amd modules i.e. `import foo = require('foo')`

以前我可以做:

import foo = require('foo');

但是现在 TypeScript (1.5) 支持 es6 模块语法,在 ES6 模块语法中实现相同的正确方法是什么。

ES6模块语法对应的语法为:

import * as foo from 'foo';

基本上将 foo 模块中的所有内容导入到名为 foo 的局部变量中。

正确的方法是继续使用旧的导入语法。新的导入语法仅适用于 ES 模块,旧的导入语法适用于 ES6 之前的模块。两者是有区别的,故意如此。 import * as foo from 'foo'导入模块'foo'的所有属性,它不导入默认值foo

From the designer of the feature:

  • 导出默认声明总是声明一个名为 default 的导出成员,并且总是作为对 exports.default 的赋值发出。换句话说,export default 始终具有 ES 模块语义。为了与 Babel 兼容,我们可以选择在模块具有默认导出时发出 __esModule 标记,但实际上我们不会将该标记用于任何事情。
  • 一个 export = 声明,它用一个不同的实体代替模块本身来导出,总是作为对 module.exports 的赋值发出。在使用 export = 的模块中进行其他导出是错误的。这是现有的 TypeScript 行为。
  • 使用 export = 导出另一个模块(内部或外部模块)的模块可以使用新的 ES6 结构导入。特别是,方便的解构导入可以与此类模块一起使用。使用 export = 导出另一个模块的模式在 .d.ts 文件中很常见,这些文件提供内部模块的 CommonJS/AMD 视图(例如 angular.d.ts) .
  • 使用 export = 导出非模块实体代替模块本身的模块必须使用现有的 import x = require("foo") 语法导入,就像今天的情况一样。

2016 年更新: TypeScript 编译器在某些时候开始允许 import * as foo from 'legacy-module-foo' 在某些情况下获取遗留模块的默认导入。 这违反了 ES6 规范 (§15.2.1.16, “The value "*" indicates that the import request is for the target module’s namespace object。”)。

当您以这种方式导入的遗留模块更新为 ES6 模块时,这些模块的“默认”导入将停止工作(因为 * as foo 导入 应该 导入 命名空间对象 ),如果您不知道这样做是 TypeScript/SystemJS 黑客攻击,这可能会非常混乱。未来 TypeScript 与 ES 规范的重新调整也可能会导致它们中断。

因此,您可能更愿意继续使用上述遗留导入语法来加载遗留模块,以避免您自己和其他处理您的代码的开发人员对 ES6 命名空间导入的工作方式感到困惑,并避免混淆破坏性更改.

ES6 modules are effectively TypeScript external modules with a new syntax: ES6 modules are separately loaded source files that possibly import other modules and provide a number of externally accessible exports. ES6 modules feature several new export and import declarations. It is recommended that TypeScript libraries and applications be updated to use the new syntax, but this is not a requirement.

Source

据我了解,这意味着我们鼓励您将自己的 TypeScript 模块迁移到新语法,但继续使用 import foo = require('foo') 导入实际的 AMD/CommonJS 模块。

TypeScript 2.7 起,有一个新的 esModuleInterop 标志可用于启用 CommonJS/AMD/UMD 的默认导入。通过在 tsconfig.json 中将该标志设置为 true,这应该会按预期工作:

import foo from 'foo';

另一种选择是使用 CommonJS 语法导入它:

const foo = require("foo");

TypeScript 和 Babel 都同意如何处理这个问题。此外,如果您正在编译为 ES5 或更低版本,那么这与最终形式不会相差太远。

全部导入,

const foo = require("foo");

这将从包 "foo" 中导入所有实例,如果它是一个文件则

const foo = require("./foo");

因此您可以通过调用 foo.InstanceName

来访问每个实例

如果要导入特定实例,

import MyInstance from "foo";

所以这将从 "foo" 导入特定实例 (Myinstance) 您仍然可以使用上述方法导入所有内容,

import * as ReferenceName from "foo";

相当于,

const ReferenceName = require("foo");