CSS
const css = () => ( src(`${SRC_DIR}**/*.css`) .pipe(dest(`${OUTPUT_DIR}css/`)) ) exports.default = series(css)
压缩css,更改文件名
npm i -D gulp-cssmin
const css = () => ( src(`${SRC_DIR}**/*.css`) .pipe(cssmin()) .pipe(rename('bundle.min.css')) .pipe(dest(`${OUTPUT_DIR}css/`)) )
配置less
npm i -D gulp-less
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/`)) )
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})) )
HTML
采用pug
const htmlTask = () => ( src(`${SRC_DIR}/view/*.pug`) .pipe(pug({ pretty: true })) .pipe(dest(`${OUTPUT_DIR}/`)) )
服务器
gulp-connect
const connectTask = () => ( connect.server({ livereload: true, root: OUTPUT_DIR }) ) const reload = () => ( src(`${OUTPUT_DIR}/**/*`) .pipe(connect.reload()) )
完整的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))