ES2015とかなんぞいって奴がちゃんと1から環境の構築をしてみる
環境
bash-3.2$ node -v v5.12.0 bash-3.2$ npm -v 3.10.6
babelのインストール
まずはbabelのインストールから始める。
npm install-D babel-cli
適当にa.jsでもつくって以下
const myfunc = (x) => { return x * x; }; console.log(myfunc(19));
いざコンパイル
./node_modules/.bin/babel a.js
ふぇえ
bash-3.2$ ./node_modules/.bin/babel a.js Error: Couldn't find preset "es2015" relative to directory "/Users/thr3a/nodejs/sugukesu2" at /Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/options/option-manager.js:313:17 at Array.map (native) at OptionManager.resolvePresets (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/options/option-manager.js:305:20) at OptionManager.mergePresets (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/options/option-manager.js:288:10) at OptionManager.mergeOptions (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:14) at OptionManager.init (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/options/option-manager.js:360:12) at File.initOptions (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/index.js:223:65) at new File (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/index.js:140:24) at Pipeline.transform (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/pipeline.js:46:16) at transform (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-cli/lib/babel/util.js:52:22)
エラーには書かれてないが原因はどのプラグインを使って変換するかがBabelがわかっていない。プラグインは別途インストールする必要がある
npm install -D babel-preset-es2015
.babelrcを直下に作成し以下
{ "presets": ["es2015"] }
再挑戦
bash-3.2$ ./node_modules/.bin/babel a.js "use strict"; var myfunc = function myfunc(x) { return x * x; }; console.log(myfunc(19));
やっためう
Gulpによるタスク管理 自動化
毎回 ./node_modules/.bin/babel a.js
叩いてたら辛いでしょう、ってことでgulpをインストール
npm install -D gulp
忘れがちだけどgulpは何もbabel専用ではない。別途橋渡しになるプラグインが必要。
npm install -D gulp-babel
mkdir src dist
で適当にディレクトリ作る。で直下に gulpfile.js を作成し以下 これがgulpの行うタスク一覧となる
var gulp = require('gulp'); var babel = require('gulp-babel'); var src_dir = './src/*.js' gulp.task('default', function () { return gulp.src(src_dir) .pipe(babel()) .pipe(gulp.dest('dist')); }); gulp.task('watch', function(){ gulp.watch(src_dir, ['default']); });
毎回./node_module/.binから叩くのもつらいのでpackage.jsonにコマンドを登録しておく。これでnpmコマンド経由で実行できる
"scripts": { "build": "gulp", "watch": "gulp watch" },
いざ実行
npm run build npm run watch
やっためう