Babelってなんなん?
ECMAScript2015以降を使用しているコードをブラウザがサポートしているレベルのECMAScriptに変換してくれるトランスパイラです。
これで、class,const,let,promise,async/awaitなんかを使用できるようになります。
node.jsのバージョンが古い場合にも使えるのかな?考えたことなかったw
gulpからBabelを使う
gulpはインストールされているものとします。
gulpプラグイン インストール
- gulp-babel
- babel-preset-latest presetはes2015,es2016,es2017と策定された物ごとに用意されていますが、全部載せたいのでlatestを使用します。
-
babel-polyfill 最新の機能をエミュレートするのに必要なライブラリです。ブラウザで使用する場合は、
node_modules/babel-polyfill/dist/polyfill.js
をhtmlで読み込む必要があります。
npm install --save-dev gulp-babel babel-preset-latest
gulpタスク
gulpfile.js
を以下の様に記載します。
タスクの内容は、jsフォルダ内の.jsファイルをトランスパイルして./dist/jsに出力です。
'use strict';
const gulp = require('gulp');
const babel = require('gulp-babel');
gulp.task('babel', function() {
gulp.src('./js/*.js')
.pipe(babel({
presets: ['latest']
}))
.pipe(gulp.dest('./dist/js'));
});
トランスパイルの例
トランスパイル前のコード
'use strict';
class Test {
constructor() {
console.log('Test.constructor');
}
log() {
console.log('test');
}
}
new Test().log();
トランスパイル後のコード
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test = function () {
function Test() {
_classCallCheck(this, Test);
console.log('Test.constructor');
}
_createClass(Test, [{
key: 'log',
value: function log() {
console.log('test');
}
}]);
return Test;
}();
new Test().log();