LoginSignup
12
16

More than 5 years have passed since last update.

Gulpで自分自身(gulpfile.js)を監視する

Last updated at Posted at 2017-04-28

Gulpで自分自身(gulpfile.js)を監視する

serve や watch などのタスクを記述するときに gulpfile.js 自身にもホットスワップが欲しいと思っていたので
https://github.com/gulpjs/gulp/issues/1009
を参考にしながら記述。

いきなり結論

const argv = require('yargs').argv;
const cp = require('child_process');

let childProcess;
function spawnChildProcess(task) {
    childProcess && childProcess.kill();
    childProcess = cp.spawn('gulp', [task], {stdio: 'inherit'});
}

gulp.task('self-watch', function () {
    const task = argv.task || 'default';

    spawnChildProcess(task);
    gulp.watch(__filename, function () {
        spawnChildProcess(task);
    });
});

使い方

gulp self-watch --task=watch

のように使う。package.json にスクリプトとして追加しておくと便利。

{
  "scripts": {
    "build": "gulp build",
    "serve": "gulp self-watch --task=serve",
    "watch": "gulp self-watch --task=watch"
  }
}

結果

Screenshot from 2017-04-29 07-51-15.png
これは便利。

12
16
0

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
12
16