LoginSignup
23
28

More than 3 years have passed since last update.

gulp 4 + Babel 7 導入

Last updated at Posted at 2019-05-10

最新版の gulp (4.0.2) と Babel (7.4.4) と gulp-babel (8.0.0) を導入した備忘録

※gulpをglobal環境にインストールしたくなかったので少し我流になっています。

最も正しい導入の手順

公式のドキュメントに勝るものなし

gulp.jsのQuick Start
https://gulpjs.com/docs/en/getting-started/quick-start

gulp-babelのREADME.md
https://github.com/babel/gulp-babel

実際に行った導入手順

準備編

  • nodeのインストール
  • npm init

このときのバージョンは↓

$ node -v
v12.2.0
$ npm -v
6.9.0

gulpのインストール

公式クイックスタートに書いてあるnpm install -g gulp-cliは省略(global汚したくないマン)

$ npm install --save-dev gulp

ローカルのgulpのバージョン見るときはnpx(npm 5.2.0から標準搭載)を使ってこう↓

$ npx gulp -v
CLI version: 2.2.0
Local version: 4.0.2

もしnpxが無い場合は下の好きな方で↓

$ $(npm bin)/gulp -v
$ ./node_modules/.bin/gulp -v

Babelのインストール

ついでにgulp-babelもインストール

$ npm install --save-dev gulp-babel @babel/core @babel/preset-env

この時点で全体のバージョンは↓

$ npm list --depth=0
gb-test@1.0.0 /Users/semi/gb-test
├── @babel/core@7.4.4
├── @babel/preset-env@7.4.4
├── gulp@4.0.2
└── gulp-babel@8.0.0

gulpの設定

gulpfile.jsを作成
srcディレクトリ内のjsファイルを全てbabelにトランスパイルしてもらって、distディレクトリに出力する設定にしました。

gulpfile.js
const gulp = require('gulp');
const babel = require('gulp-babel');

gulp.task('babel', () => {
    return gulp.src('src/*.js')
        .pipe(babel({
            presets: ['@babel/preset-env']
        }))
        .pipe(gulp.dest('dist'));
});

(ほぼgulp-babelのドキュメント通りですが、5行目のreturnが無いとgulpにDid you forget to signal async completion?と煽られるので追加しています。)

gulpの実行

この状態でgulp babelと実行してもglobalにgulp-cliをインストールしていないため怒られます。
そこでnpxを使ってローカルのgulpを呼びます。

$ npx gulp babel

でgulpfile.jsに書いた"babel"タスクを実行します。

gulpの実行(npm scriptsから)

npm run ~の形でgulpを呼びたいときは

package.json
...
  "scripts": {
    "gulp": "gulp"
  },
...

と書いておけばnpm run gulpでローカルのgulpが呼び出せます。

$ npm run gulp babel

でgulpfile.jsに書いた"babel"タスクを実行します。

おまけ:ファイルの変更を監視して自動でバベる

gulpfile.jsに以下を追記

gulpfile.js
...
gulp.task('watch', () => {
    gulp.watch('src/*.js', gulp.series('babel'));
});
$ npx gulp watch

もしくは

$ npm run gulp watch

で監視を開始します。

23
28
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
28