1. gulp 入口文件 gulpfile.js
exports.foo = done => {
console.log('foo task working');
done();//任务完成
}
exports.default = done => {
console.log('default task woking');
done();
}
传统做法,推荐以上做法
const gulp = require('gulp')
gulp.task('bar',done => {
console.log('bar working');
done()
})
2. 介绍series、parallel,前者依次触发,后者并行触发
const { series, parallel} = require('gulp')
const task1 = done =>{
setTimeout(() => {
console.log('task1 working')
done()
},1000)
}
const task2 = done => {
setTimeout(() => {
console.log('task2 working')
done()
},1000)
}
const task3 = done => {
setTimeout(() => {
console.log('task3 working')
done()
},1000)
}
exports.foo = series(task1 , task2 , task3)
exports.bar = parallel(task1, task2, task3)
3.异步回调
exports.callback = done => {
console.log('callback task--');
done();
}
exports.callback_error = done => {
console.log('error');
done(new Error('task falled'))
}
exports.promise = () => {
console.log('promise task...');
// return Promise.resolve();
return Promise.reject(new Error('task falled...'))
}
const timeout = time => {
return new Promise(resolve => {
setTimeout(resolve,time)
})
}
exports.async = async() => {
await timeout(1000)
console.log('async task...');
}
const fs = require('fs')
exports.stream = () => {
const readStream = fs.createReadStream('package.json')
const writeStream = fs.createWriteStream('temp.txt')
readStream.pipe(writeStream)
return readStream//存在end结束事件
}
4. 构建过程中核心原理
//读取流 》 转换流 》 写入流
const fs = require('fs')
const { Transform } = require('stream')
exports.default = () => {
//文件读取流
const read = fs.createReadStream('demo.css')
//文件写入流
const write = fs.createWriteStream('demo.min.css')
//文件转换流
const transform = new Transform({
transform: (chunk, ecodeing, callback) => {
//核心转换过程实现
//chunk => 读取流中读取到的内容 (Buffer)
const input = chunk.toString();
const output = input.replace(/\s+/g,'').replace(/\/\*.+?\*\//g,'')
callback(null,output)
}
})
//把读取出来的文件流写入文件流
read
.pipe(transform)//转换
.pipe(write)//转入
return read
}
5.文件操作API
const {src, dest} = require('gulp')
//安装插件 gulp-clean-css
//安装插件 gulp-rename
const cleancss = require('gulp-clean-css')
const rename = require('gulp-rename')
exports.default = () => {
return src('src/*.css')
.pipe(cleancss())
.pipe(rename({extname: '.min.css'}))
.pipe(dest('dist'))
}
6. 自动化构建案例
const { src, dest, parallel, series, watch } = require('gulp')
//建立temp,防止边读取边写入造成文件无法生成问题
//区别开发时build和上线之前构建,建立个临时目录temp,最终上线用dist
const del = require('del')
// yarn add browser-sync --dev
const browserSync = require('browser-sync')
const loadPlugins = require('gulp-load-plugins')
//自动加载插件 yarn add gulp-load-plugins --dev
const plugins = loadPlugins()
//创建开发服务器
const bs = browserSync.create()
const data = {
menus: [
{
name: 'Home',
icon: 'aperture',
link: 'index.html'
},
{
name: 'Features',
link: 'features.html'
},
{
name: 'About',
link: 'about.html'
},
{
name: 'Contact',
link: '#',
children: [
{
name: 'Twitter',
link: 'https://twitter.com/w_zce'
},
{
name: 'About',
link: 'https://weibo.com/zceme'
},
{
name: 'divider'
},
{
name: 'About',
link: 'https://github.com/zce'
}
]
}
],
pkg: require('./package.json'),
date: new Date()
}
const clean = () => {
//安装 yarn add del --dev
return del(['dist', 'temp'])
}
const style = () => {
//安装 yarn add gulp-sass --dev
return src('src/assets/styles/*.scss', { base: 'src' })
.pipe(plugins.sass({ outputStyle: 'expanded' }))
.pipe(dest('temp'))
.pipe(bs.reload({ stream: true }))//以流的形式推到浏览器
}
const script = () => {
//安装 yarn add gulp-babel --dev
// yarn add @babel/core @babel/preset-env --dev
return src('src/assets/scripts/*.js', { base: 'src' })
.pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
.pipe(dest('temp'))
.pipe(bs.reload({ stream: true }))
}
const page = () => {
return src('src/*.html', { base: 'src' })
.pipe(plugins.swig({ data, defaults: { cache: false } })) // 防止模板缓存导致页面不能及时更新
.pipe(dest('temp'))
.pipe(bs.reload({ stream: true }))
}
const image = () => {
//yarn add gulp-imagemin --dev
return src('src/assets/images/**', { base: 'src' })
.pipe(plugins.imagemin())
.pipe(dest('dist'))
}
const font = () => {
return src('src/assets/fonts/**', { base: 'src' })
.pipe(plugins.imagemin())
.pipe(dest('dist'))
}
const extra = () => {
//拷贝
return src('public/**', { base: 'public' })
.pipe(dest('dist'))
}
//初始化服务器配置
const serve = () => {
//监听源文件变化
watch('src/assets/styles/*.scss', style)
watch('src/assets/scripts/*.js', script)
watch('src/*.html', page)
// watch('src/assets/images/**', image)
// watch('src/assets/fonts/**', font)
// watch('public/**', extra)
//减少构建次数
watch([
'src/assets/images/**',
'src/assets/fonts/**',
'public/**'
], bs.reload)
bs.init({
notify: false,//服务器提示
port: 2080,//端口
// open: false,//默认开启浏览器
// files: 'dist/**',//指定dist文件发生改变及时热部署
server: {
baseDir: ['temp', 'src', 'public'],//设置根目录
routes: {//特殊路由,优先basedir从这里寻找文件
'/node_modules': 'node_modules' }
}
})
}
const useref = () => {
//yarn add gulp-useref --dev
return src('temp/*.html', { base: 'temp' })
.pipe(plugins.useref({ searchPath: ['temp', '.'] }))
// html js css
//yarn add gulp-htmlmin gulp-uglify gulp-clean-css --dev
//yarn add gulp-if --dev
.pipe(plugins.if(/\.js$/, plugins.uglify()))
.pipe(plugins.if(/\.css$/, plugins.cleanCss()))
.pipe(plugins.if(/\.html$/, plugins.htmlmin({
collapseWhitespace: true,//删除空格
minifyCSS: true,//压缩行内样式
minifyJS: true//压缩行内js
})))
.pipe(dest('dist'))
}
const compile = parallel(style, script, page)
// 上线之前执行的任务
const build = series(
clean,
parallel(
series(compile, useref),//useref依赖compile
image,
font,
extra
)
)
//开发时执行
const develop = series(compile, serve)
module.exports = {
clean,
build,
develop
}
7.封装工作流