1. 程式人生 > >前端工具-ES6相關工具

前端工具-ES6相關工具

處理ES6語法

使用Babel

Babel是一個用於將ECMAScript 2015+ 程式碼轉換為新舊瀏覽器或其他環境支援的JavaScript向下相容版本程式碼的工具鏈。

Babel主要可以做:

  • 語法翻譯
  • 拓展(Polyfill)您的目標環境不支援的特性
  • 原始碼轉換

處理ES6的module

  1. 使用Babel的外掛babel-plugin-transform-es2015-modules-commonjs · Babel將module轉化為commonjs
  2. 使用用Rollup或者webpack打包

支援ES6新的API(Promise等)

使用babel-polyfill

這個外掛是要寫入到最後生成的JS檔案中的,在瀏覽器執行JS時先執行polyfill將特性加到全域性環境(生成器函式倒是需要翻譯原始碼)。

使用babel-plugin-transform-runtime可以複用Babel注入的幫助程式碼,減小程式碼體積。

相關資料:

This means you can use new built-ins like Promise or WeakMap, static methods like Array.from or Object.assign, instance methods like Array.prototype.includes, and generator functions (provided you use the regenerator plugin). The polyfill adds to the global scope as well as native prototypes like String in order to do this.

http://www.ruanyifeng.com/blog/2016/01/babel.html
Babel 預設只轉換新的 JavaScript 句法(syntax),而不轉換新的 API ,比如 Iterator、Generator、Set、Maps、Proxy、Reflect、Symbol、Promise 等全域性物件,以及一些定義在全域性物件上的方法(比如 Object.assign)都不會轉碼。Babel 預設不轉碼的 API 非常多,詳細清單可以檢視 definitions.js 檔案

http://babeljs.io/docs/en#polyfill
Since Babel only transforms syntax (like arrow functions), you can use babel-polyfill in order to support new globals such as Promise or new native methods like String.padStart (left-pad). It uses core-js and regenerator. Check out our babel-polyfill docs for more info.

支援ES6的fetch

babel-polyfill不支援fetch,得用github/fetch: A window.fetch JavaScript polyfill.

相關資料:

作者說fetch不是跨平臺特性,在一些環境中它沒有意義就沒加進來

window.fetch is not a cross-platform feature, in some environments it makes no sense. For this reason, I don't think it should be in core-js. Looking at a large number of requests it may be added in the future. Now you can use, for example, this polyfill.