gulp4进阶

CSS

const css = () => (
  src(`${SRC_DIR}**/*.css`)
    .pipe(dest(`${OUTPUT_DIR}css/`))
)


exports.default = series(css)
View Code

  压缩css,更改文件名

npm i -D gulp-cssmin
View Code
const css = () => (
  src(`${SRC_DIR}**/*.css`)
    .pipe(cssmin())
    .pipe(rename('bundle.min.css'))
    .pipe(dest(`${OUTPUT_DIR}css/`))
)
View Code

  配置less

npm i -D gulp-less
View Code
const cssTask = () => (
  src([`${SRC_DIR}/assets/style/reset.css`, `${SRC_DIR}/assets/style/**/*.less`])
    .pipe(less())
    .pipe(concat('bundle.css'))
    .pipe(postcss([autoprefixer()]))
    .pipe(dest(`${OUTPUT_DIR}/css/`))
)
View Code

JS

  gulp-uglify

    压缩JS文件

  gulp-babel

    编译es6,但是gulp-concat是粗暴的合并文件,所以如果js中使用import/export语法浏览器会报错

  webpack-stream、 vinyl-named

    通过webpack解决import/export语法报错

const jsTask = () => (
  src(`${SRC_DIR}/**/*.js`, {sourcemaps: true})
    .pipe(named())
    .pipe(webpack({mode:'development'}))
    .pipe(concat('bundle.js'))
    .pipe(dest(`${OUTPUT_DIR}/js/`, {sourcemaps: true}))
)
View Code

HTML

  采用pug

const htmlTask = () => (
  src(`${SRC_DIR}/view/*.pug`)
    .pipe(pug({
      pretty: true
    }))
    .pipe(dest(`${OUTPUT_DIR}/`))
)
View Code

服务器

  gulp-connect

const connectTask = () => (
  connect.server({
    livereload: true,
    root: OUTPUT_DIR
  })
)

const reload = () => (
  src(`${OUTPUT_DIR}/**/*`)
    .pipe(connect.reload())
)
View Code

完整的gulfile.js

const SRC_DIR = 'src'
const OUTPUT_DIR = 'dist'
const STYLE_SRC_DIR = `${SRC_DIR}/assets/style`
const STYLE_OUTPUT_DIR = `${OUTPUT_DIR}/css`
const HTML_SRC_DIR = `${SRC_DIR}/views`
const HTML_OUTPUT_DIR = `${OUTPUT_DIR}`
const JS_SRC_DIR = `${SRC_DIR}/utils`
const JS_OUTPUT_DIR = `${OUTPUT_DIR}/js`

const { src, dest, series, parallel, watch } = require('gulp')
const concat = require('gulp-concat')
const less = require('gulp-less')
const pug = require('gulp-pug')
const uglify = require('gulp-uglify')
const connect = require('gulp-connect')

const styleTask = () => (
  src([`${STYLE_SRC_DIR}/reset.css`, `!${STYLE_SRC_DIR}/common.less`, `${STYLE_SRC_DIR}/*.less`])
    .pipe(less())
    .pipe(concat('bundle.css'))
    .pipe(dest(STYLE_OUTPUT_DIR))
    .pipe(connect.reload())
)

const htmlTask = () => (
  src(`${HTML_SRC_DIR}/*.pug`)
    .pipe(pug({
      pretty: true
    }))
    .pipe(dest(`${HTML_OUTPUT_DIR}`))
    .pipe(connect.reload())
)

const jsTask = () => (
  src(`${JS_SRC_DIR}/**/*`)
    .pipe(uglify())
    .pipe(concat('bundle.js'))
    .pipe(dest(`${JS_OUTPUT_DIR}`))
    .pipe(connect.reload())
)

const connectTask = () => (
  connect.server({
    root: OUTPUT_DIR,
    livereload: true
  })
)

exports.default = parallel(styleTask, htmlTask, jsTask, connectTask)

watch(`${STYLE_SRC_DIR}/*`, series(styleTask))
watch(`${HTML_SRC_DIR}/*.pug`, series(htmlTask))
watch(`${JS_SRC_DIR}/**/*`, series(jsTask))
View Code
原文地址:https://www.cnblogs.com/sonwrain/p/12540255.html