简体   繁体   English

如何将 TypeScript 转译为 ES6?

[英]How do I transpile TypeScript to ES6?

Basically I need to be able to write TypeScript code in my IDE (this introduces great ease to development), compile it to ES6 and then apply babel.js (as all browsers doesn't support most ES6) to get the resulting ES5 scripts.基本上,我需要能够在我的 IDE 中编写 TypeScript 代码(这为开发带来了极大的便利),将其编译为 ES6,然后应用babel.js (因为所有浏览器不支持大多数 ES6)以获取生成的 ES5 脚本。

Is this possible?这可能吗? How can I achieve this?我怎样才能做到这一点?

Yes.是的。

You can target TypeScript compiler to ES6.您可以将 TypeScript 编译器定位到 ES6。

For example add this to your command line args:例如,将此添加到您的命令行参数中:

--target es6

Yes, You can.是的你可以。

Either by adding --target es2015 , or by adding target to Your tsconfig.json :通过添加--target es2015 ,或通过将target添加到您的tsconfig.json

{
  "compilerOptions": {
    "target": "es2015"
  }
}

Supported options for target are:支持的目标选项有:

  • "ES3" (default) “ES3”(默认)
  • "ES5" “ES5”
  • "ES6"/"ES2015" “ES6”/“ES2015”
  • "ES2016" “ES2016”
  • "ES2017" “ES2017”
  • "ESNext" “ESNext”

There are a lot of more config options.还有很多配置选项。 You can explore them here: Compiler options你可以在这里探索它们: 编译器选项

Some options are only allowed in tsconfig.json , and not through command-line switches.某些选项仅允许在tsconfig.json ,而不能通过命令行开关使用。

You can use typescript to write pure ES6 and then transpile to ES3 or ES5.您可以使用 typescript 编写纯 ES6,然后转译为 ES3 或 ES5。 Since typescript is ES6 plus goodies.因为打字稿是 ES6 加上好东西。

See it as using Less to write your css, you can write pure CSS in a less file and it will compile just fine.将其视为使用 Less 编写 css,您可以在 less 文件中编写纯 CSS,它会编译得很好。

For typescript 1.8 language spec:对于打字稿 1.8 语言规范:

TypeScript is a syntactic sugar for JavaScript. TypeScript 是 JavaScript 的语法糖。 TypeScript syntax is a superset of ECMAScript 2015 (ES2015) syntax. TypeScript 语法是 ECMAScript 2015 (ES2015) 语法的超集。 Every JavaScript program is also a TypeScript program.每个 JavaScript 程序也是一个 TypeScript 程序。

TypeScript syntax includes all features of ECMAScript 2015, including classes and modules, and provides the ability to translate these features into ECMAScript 3 or 5 compliant code. TypeScript 语法包括 ECMAScript 2015 的所有功能,包括类和模块,并提供将这些功能转换为 ECMAScript 3 或 5 兼容代码的能力。

TypeScript is more or less ES6 with very little syntactic sugar. TypeScript 或多或少是 ES6,语法糖很少。 I would suggest you write Vanilla ES6 instead of TypeScript but on the other hand TypeScript tooling is worth putting in the extra effort to write TypeScript and transpile it into ES6 and let Babel do the rest.我建议您编写 Vanilla ES6 而不是 TypeScript,但另一方面,TypeScript 工具值得付出额外的努力来编写 TypeScript 并将其转换为 ES6,然后让 Babel 完成剩下的工作。

Here is a more convenient option like noted in a comment, from TypeScript 1.5 you have the ability to transpile to ES6.这是一个更方便的选项,如注释中所述,从 TypeScript 1.5 开始,您可以转译为 ES6。

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

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