Gulp4 Koa專案簡單配置示例

weixin_34127717發表於2019-01-20

介紹

這段配置是之前的gulp版本不適配新版本node後,更新到了gulp4的新寫法。

在業務中,目前使用這份配置的是一個Koa2+njk專案,所以增加了nodemon來啟動server。

分別用到的技術為:

  • Less + autoprefixer + cleancss + sourceMap
  • Js + es6(babel) + uglify + sourceMap
  • BrowserSync For auto reload
  • Nodemon for restart Koa2 server

配置

廢話不多說,上程式碼:

/*
 * Gulp4通用配置
 * Author: Kinice
 * Time: 2018-12-26
 */
const gulp = require('gulp')
const path = require('path')
const less = require('gulp-less')
const browserSync = require('browser-sync').create()
const reload = browserSync.reload
const cleancss = require('gulp-cssnano')
const autoprefixer = require('gulp-autoprefixer')
const pump = require('pump')
const uglify = require('gulp-uglify')
const sourcemaps = require('gulp-sourcemaps')
const babel = require('gulp-babel')
const nodemon = require('gulp-nodemon')
const changed = require('gulp-changed')
const config = require('./config')
const port = process.env.PORT || config.port

// 將所需的資源path放到一起便於管理
const paths = {
  style: {
    src: 'src/less/**/*.less',
    dest: 'public/css/'
  },
  script: {
    src: 'src/js/**/*.js',
    dest: 'public/js/'
  },
  view: {
    src: 'views/**/*.njk',
    dest: 'views/'
  }
}

// 處理less的task
function style(callback) {
  // pump提供了中斷pipe的callback
  return pump([
    gulp.src(path.join(__dirname, paths.style.src)),
    // 開啟sourcemap以方便除錯
    sourcemaps.init(),
    less(),
    autoprefixer({
      browsers: [
        '>1%',
        'last 10 version',
        'iOS >= 8'
      ]
    }),
    cleancss(),
    sourcemaps.write('maps'),
    gulp.dest(path.join(__dirname, paths.style.dest)),
    reload({
      stream: true
    })
  ], callback)
}

// 處理js的task
function script(callback) {
  return pump([
    gulp.src(path.join(__dirname, paths.script.src)),
    sourcemaps.init(),
    babel(),
    uglify(),
    sourcemaps.write('maps'),
    gulp.dest(path.join(__dirname, paths.script.dest))
  ], callback)
}

// 監測檔案修改並呼叫相應task之後重新整理頁面
function watch() {
  gulp.watch(path.join(__dirname, paths.style.src), style)
  gulp.watch(path.join(__dirname, paths.script.src), script)

  gulp.watch(path.join(__dirname, `${paths.style.dest}*.css`)).on('change', reload)
  gulp.watch(path.join(__dirname, `${paths.script.dest}*.js`)).on('change', reload)
  gulp.watch(path.join(__dirname, `${paths.view.dest}*.njk`)).on('change', reload)
}

// 使用nodemon啟動node server,如果不含node就去掉
function server() {
  nodemon({
    script: 'app.js'
  })
  browserSync.init({
    proxy: `http://localhost:${port}`
  })
}

exports.style = style
exports.script = script
exports.watch = watch

// 同步執行script和style task
let build = gulp.parallel(script, style)

// 先build,再同步啟動node server和開啟檔案監測
gulp.task('default', gulp.series(build, gulp.parallel(server, watch)))

相關文章