[Babel] Babel: ブラウザ向けに Polyfill ライブラリを有効化する
前回の続き。
babel-polyfill/dist/polyfill.js を読み込む。
[markdown]
“`prettyprinted
% $(npm bin)/babel
6.6.5 (babel-core 6.7.4)
“`
> * [Babel: ES6 -> ES5 へトランスコンパイルする | deadwood](https://www.d-wood.com/blog/2016/04/11_7913.html)
## Polyfill とは
トランスコンパイルができるようになったが、ブラウザで ES6 をフル利用するためには Polyfill ライブラリを読み込む必要がある。
> * [Babelを使って次期JavaScript、ES6を体験しよう : アシアルブログ](http://blog.asial.co.jp/1434)
>
> ブラウザで、Babelで変換したコードを利用する場合、ポリフィルが必要になります。ポリフィルとはES6の新しい機能などを利用するためのES5向けのライブラリです。変換だけでは、ポリフィルは含まれないので、babel-coreパッケージをプロジェクトにインストールする必要があります。
## Polyfill を追加する
Polyfill ライブラリを有効化するために html に polyfill.js を読み込む設定を加える。
> * [Polyfill · Babel](https://babeljs.io/docs/usage/polyfill/)
>
> Usage in Browser
>
> Available from the dist/polyfill.js file within a babel-polyfill npm release. This needs to be included before all your compiled Babel code. You can either prepend it to your compiled code or include it in a <script> before it.
>
> NOTE: Do not require this via browserify etc, use babel-polyfill.
コンパイル後のコードの前にインクルードするか、<script> タグで事前に読み込むかということなので、後者で対応する。
### HTML ファイルを作成する
babel-cli インストール時に同梱されていた `node_modules/babel-polyfill/dist/polyfill.js` を読み込む。
“`html:index.html
“`
ファイル構成は下記のようになった。
“`prettyprinted
.
├── index.html
├── lib
│ ├── basic.js
│ └── basic.js.map
├── package.json
└── src
└── basic.es6
“`
## 動作確認
Babel 公式を確認すると Support via polyfill という記述があり、これが対象となる。
> * [Learn ES2015 · Babel](https://babeljs.io/docs/learn-es2015/)
ES6 の対応状況は、下記のサイトが参考にされているようだ。
> * [ECMAScript 6 compatibility table](http://kangax.github.io/compat-table/es6/)
例えば Promise はポリフィルが必要との事。
> * [Promise – JavaScript | MDN](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise)
### サンプルコードを追加する
動作確認のために Promise を利用したコードを追加する。
が、自分の JavaScript 力がゼロのため、下記を参考にさせて頂く。
> * [Rubyist Magazine – 2015 年の JavaScript と babel の話](http://magazine.rubyist.net/?0050-ECMAScript2015)
“`javascript:src/basic.es6
‘use strict’;
let i = [1, 2, 3].map(n => n + 1);
console.log(i);
document.write(i);
function timeout(ms) {
// Promise の resolve 関数を受け取る
return new Promise((onFulfilled, onRejected) => {
// 50% の確率で onFulfilled, onRejected が呼ばれる
setTimeout(() => Math.random() > 0.5 ? onFulfilled() : onRejected(), ms);
});
}
function log() {
console.log(‘done’);
}
function error() {
console.log(‘error’);
}
// onFulfilled が出たら done、onRejected だったら error と表示する
timeout(100).then(log).catch(error);
“`
手元の Mac/Chrome と Win/IE9 で確認したところ、期待したとおりの動作をした。
ちなみに polyfill.js を取り除いた場合、Win/IE9 では下記のエラーとなる。
[/markdown]