简体   繁体   中英

Can we write TypeScript modules in another format besides ES6?

For example, can we write using 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.

In your example, the compiler would complain about define :

error TS2304: Cannot find name 'define'.

You need to tell the compiler that define exists before you use it:

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. 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. That isn't something that is built into TypeScript. TypeScript is just a super set of JavaScript.

Using TypeScript enables compiler type checking, and allows you to use newer JavaScript features, while compiling to older versions of 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.

To that end, as another answer points out, you can also write modules using the ES6 syntax, and compile them to the amd format. From the documentation at 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. For more information on what the define, require and register calls in the generated code do, consult the documentation for each module loader.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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