dayjournal memo

Total 975 articles!!

gulp #003 – gulpでファイルを監視

Yasunori Kirimoto's avatar

今回は、「gulp」でファイルを監視する方法を試したいと思います。

node.js_016_02


まず、サンプルとしてsampleフォルダに「index.html」を用意します。 node.js_017_01


index.html


<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <title>sample</title>
</head>

<body>

    <p>サンプル!</p>

</body>

</html>

「gulpfile.js」にgulp.watchメソッドを追加記述します。

gulpfile.js


var gulp = require('gulp');

gulp.task('sample', function() {
    gulp.src('./sample/index.html')
        .pipe(gulp.dest('./dist'));
});

gulp.task('watch', function() {
    gulp.watch('./sample/index.html', ['sample']);
});

gulp.task('default', ['sample', 'watch'])

作業フォルダでgulpを実行すると「dist」フォルダが作成され「index.html」がコピーされます。そして指定したファイルが監視状態になります。


gulp

node.js_018_01


node.js_017_02


「sample」フォルダの「index.html」を更新すると、リアルタイムで「dist」フォルダの「index.html」も更新されます。

node.js_018_02


パスと監視するタスクを指定:


gulp.task('watch', function() {
    gulp.watch('./sample/index.html', ['sample']);
})

watchタスクを追加:


gulp.task('default', ['sample', 'watch'])

任意ファイルを監視してリアルタイムで更新を反映できるので便利です。



book

Q&A