Gulp4 Koa项目简朴设置示例

引见

这段设置是之前的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)))
    原文作者:Kinice
    原文地址: https://segmentfault.com/a/1190000017958408
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞