简体   繁体   English

我们可以用 ES6 以外的其他格式编写 TypeScript 模块吗?

[英]Can we write TypeScript modules in another format besides ES6?

For example, can we write using AMD?例如,我们可以使用 AMD 编写吗?

define([
  'hb!./some/file.hb'
], function(template) {
  //
})

To some extent, yes.在某种程度上,是的。

Because TypeScript is just a superset of JavaScript, any valid JavaScript is also valid TypeScript.因为 TypeScript 只是 JavaScript 的超集,所以任何有效的 JavaScript 也是有效的 TypeScript。

In your example, the compiler would complain about define :在您的示例中,编译器会抱怨define

error TS2304: Cannot find name 'define'.错误 TS2304:找不到名称“定义”。

You need to tell the compiler that define exists before you use it:在使用之前,您需要告诉编译器define存在:

declare var define;

define([
  'hb!./some/file.hb'
], function(template) {
  //
})

This will let the compiler know that define exists, but it does not provide the compiler with any additional information about it.这将让编译器知道define存在,但它不会向编译器提供有关它的任何附加信息。 So, another solution would be to add the proper type definition .因此,另一种解决方案是添加正确的类型定义

To consume amd modules, you will still need to include an amd module loader.要使用amd模块,您仍然需要包含amd模块加载器。 That isn't something that is built into TypeScript.这不是 TypeScript 内置的东西。 TypeScript is just a super set of JavaScript. TypeScript 只是 JavaScript 的超级集。

Using TypeScript enables compiler type checking, and allows you to use newer JavaScript features, while compiling to older versions of JavaScript.使用 TypeScript 可以启用编译器类型检查,并允许您使用较新的 JavaScript 功能,同时编译为较旧版本的 JavaScript。 However, TypeScript won't be able to understand what it is that another module exports, therefore you will need a declaration for each AMD module describing what the module exports.但是,TypeScript 将无法理解另一个模块导出的内容,因此您需要为每个 AMD 模块声明一个描述模块导出内容的声明。

To that end, as another answer points out, you can also write modules using the ES6 syntax, and compile them to the amd format.为此,正如另一个答案指出的那样,您还可以使用 ES6 语法编写模块,并将它们编译为amd格式。 From the documentation at TypeScriptLang.org :来自TypeScriptLang.org的文档:

Depending on the module target specified during compilation, the compiler will generate appropriate code for Node.js (CommonJS), require.js (AMD), isomorphic (UMD), SystemJS, or ECMAScript 2015 native modules (ES6) module-loading systems.根据编译期间指定的模块目标,编译器将为 Node.js (CommonJS)、require.js (AMD)、同构 (UMD)、SystemJS 或 ECMAScript 2015 原生模块 (ES6) 模块加载系统生成适当的代码。 For more information on what the define, require and register calls in the generated code do, consult the documentation for each module loader.有关生成代码中的定义、要求和注册调用功能的更多信息,请参阅每个模块加载器的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM