简体   繁体   English

Typescript转换是否可以将ES6转换为ES5?

[英]Does Typescript transpilation handle transpiling ES6 to ES5?

I am writing an app using Angular 2 and TypeScript. 我正在使用Angular 2和TypeScript编写应用程序。 I want to use a js method (particularly 'filter' for arrays) which is supported by IE 11+, Chrome 45+, etc. Will my code be able to run on older browsers? 我想使用IE 11 +,Chrome 45+等支持的js方法(尤其是数组的'过滤器')。我的代码是否可以在旧版浏览器上运行? As Typescript transpiles to vanilla js, I am not sure what it does with ES6 features. 由于Typescript转换为vanilla js,我不确定它对ES6功能的作用。

TypeScript allows you to use new language features from ES6 and it will transpile those language features to ES5; TypeScript允许您使用ES6中的新语言功能 ,它会将这些语言功能转换为ES5; however, it does not add polyfills for built in functions that exist in ES6, but don't exist in ES5. 但是,它不会为ES6中存在的内置函数添加polyfill,但在ES5中不存在。

If you are using built in functions that only exist in ES6 and are targeting ES5, then you will need to include the necessary polyfills in order for the code to work in ES5 environments. 如果您使用的是仅存在于ES6中且面向ES5的内置函数,则需要包含必要的polyfill,以使代码在ES5环境中工作。

Example

For example, fill is a new function found on Array 's prototype in ES6. 例如, fill是在ES6中Array的原型中找到的新函数。

const result = ["first", "second"].fill("all");

When you target ES6 everything is fine. 当你瞄准ES6时一切都很好。 The compiler will include lib.es6.d.ts with the definition for fill and not complain because it assumes you will be running the code in ES6 environments where the fill function exists. 编译器将包含lib.es6.d.ts以及fill的定义而不是抱怨,因为它假定您将在存在fill函数的ES6环境中运行代码。

When you target ES5, however, it won't include lib.es6.d.ts and will tell you that function doesn't exist in ES5 environments: 但是,当您定位ES5时,它将不包含lib.es6.d.ts并且会告诉您ES5环境中不存在该功能:

error TS2399: Property 'fill' does not exist on type 'string[]'. 错误TS2399:类型'string []'上不存在属性'fill'。

To fix that, you'll need to add fill to the Array<T> interface in a definition file in your project: 要解决此问题,您需要在项目的定义文件中向Array<T>接口添加fill

interface Array<T> {
    fill(value: T, start?: number, end?: number): this;
}

And include a polyfill . 并包括一个polyfill Or use something that does it automatically for you. 或者使用自动为您做的事情。

Yes it can if you set tsconfig.json to target ES5 是的,如果您将tsconfig.json设置为目标ES5,则可以

set target: "ES5" in tsconfig.json compiler options or --target ES5 for CLI 设置target: "ES5" tsconfig.json编译器选项中的target: "ES5"--target ES5 for CLI

As for built-in features of ES6, IDK, but I would add the babel-loader to webpack, grunt, gulp, etc, to automatically polyfill those features. 至于ES6,IDK的内置功能,但我会将babel-loader添加到webpack,grunt,gulp等,以自动填充这些功能。

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

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