LoginSignup
4
2

More than 3 years have passed since last update.

gulp v3からv4への記述法移行

Last updated at Posted at 2019-08-09

gulp.jsがv4になり、gulp.taskが非推奨になったとのことで、それを使用しない記述方法をメモも兼ねて記事として残します。

自動化処理について

gulpfile.jsでは以下を自動化しています。

  • ローカルサーバ起動
  • ファイル変更監視してのブラウザ自動リロード
  • Sassファイル -> CSSファイルへの自動コンパイル

v3までの記述方法

const gulp = require('gulp')
const sass = require('gulp-sass')
const browserSync = require('browser-sync')

// ローカルサーバ起動
gulp.task('build-server', function(done) {
  browserSync.init({
    server: {
      baseDir: './'
    }
  })
  done()
})

// ブラウザ自動リロード
gulp.task('browser-reload', function(done) {
  browserSync.reload()
  done()
})

// Sassファイルのコンパイル
gulp.task('sass-compile', function(done) {
  gulp
    .src('sass/*.scss')
    .pipe(
      sass({
        outputStyle: 'expanded'
      })
    )
    .pipe(gulp.dest('css'))
  done()
})

// ファイル監視
gulp.task('watch-files', function() {
  gulp.watch('./*.html', gulp.task('browser-reload'))
  gulp.watch('./sass/*.scss', gulp.series('sass-compile', 'browser-reload'))
})

// タスク実行
gulp.task('default', gulp.series('build-server', 'watch-files'))

v4での記述方法

const { src, dest, watch, series, parallel } = require('gulp')
const sass = require('gulp-sass')
const browserSync = require('browser-sync')

// ローカルサーバ起動
const buildServer = done => {
  browserSync.init({
    server: {
      baseDir: './'
    }
  })
  done()
}

// ブラウザ自動リロード
const browserReload = done => {
  browserSync.reload()
  done()
}

// Sassファイルのコンパイル
const sassCompile = done => {
  src('sass/*.scss')
    .pipe(
      sass({
        outputStyle: 'expanded'
      })
    )
    .pipe(dest('css'))
  done()
}

// ファイル監視
const watchFiles = () => {
  watch('./*.html', browserReload)
  watch('./sass/*.scss', series(sassCompile, browserReload))
}

// タスク実行
exports.default = series(buildServer, watchFiles)

まとめ

gulp.task...gulp.task...が無くなっただけでもだいぶコードの見通しがよくなった気がします。
非推奨ということは将来的に廃止される可能性も考えられるので、はやめにv4流の記述方法に慣れるようにしましょう。

参考リンク

4
2
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
4
2