Gulp 使用
Gulp 基本使用
gulp :高效,易用,在项目中先安装项目依赖,导出相关函数方式
yarn init --yes
yarn add gulp --dev
code gulpfile.js
// gulp的入口文件,默认开启异步任务
exports.foo = done =>{
console.log('foo start')
done(); // 标识任务完成
}
exports.default = done =>{ // 默认任务
console.log('default start')
done();
}
运行命令
yarn gulp foo 或者 yarn gulp //默认找到default运行
Gulp 组合任务
创建并行任务
创建串行任务
const {series,parallel} =require('gulp')
const task1 = done =>{
setTimeout(()=>{
console.log('task1 start')
done();
},1000)
}
const task2 = done =>{
setTimeout(()=>{
console.log('task2 start')
done();
},1000)
}
const task3 = done =>{
setTimeout(()=>{
console.log('task3 start')
done();
},1000)
}
exports.foo = series(task1,task2,task3) //串行执行 series 是一个函数,会按照顺序依次执行任务
exports.bar = parallel(task1,task2,task3) // 并行执行
Gulp 异步任务
异步任务的三种方式
回调
exports.callback = done =>{
console.log('callback task')
done()
}
exports.callback_error = done =>{
console.log('callback task')
done(new Error('task failed!'))
}
Promise
exports.promise = () =>{
console.log('promise task')
return Promise.resolve()
}
exports.promise_error = () =>{
console.log('promise task')
return Promise.reject(new Error('task failed!'))
}
async awit
const timeout = time =>{
return new Promise(resolve=>{
setTimeout(resolve,time)
})
}
exports.async = async() =>{
await timeout(1000) // 等待promise的resolve,resolve之后会执行后续代码
console.log('async task')
}
fs
const fs = require('fs');
exports.stream = ()=>{
const readStream = fs.createReadStream('package.json');
const writeStream = fs.createWriteStream('temp.txt')
readStream.pipe(writeStream)
return readStream
}
exports.stream = done =>{
const readStream = fs.createReadStream('package.json');
const writeStream = fs.createWriteStream('temp.txt')
readStream.pipe(writeStream)
readStream.on('end',()=>{
done()
})
}
构建过程核心原理
gulp 是基于流的构建系统,gulp是实现构建管道的方式
const fs = require('fs');
const { Transform } = require('stream');
exports.default = () =>{
// 文件读取流
const read = fs.createReadStream('package.json')
// 文件写入流
const write = fs.createWriteStream('package.txt')
// 文件转换流
const transform = new Transform({
transform:(chunk,encoding,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
}
文件操作API + 插件的使用
gulp 功能更强大
yarn add gulp-clean-css --dev
yarn add gulp-rename --dev
const {src,dest} = require('gulp')
exports.default = () =>{
return src('src/normalize.css').pipe(dest('dist'))
}
const {src,dest} = require('gulp')
const cleanCss = require('gulp-clean-css') //压缩 ,需要安装插件
const rename = require('gulp-rename') //重命名
exports.default = () =>{
return src('src/*.css') // src下所有css文件
.pipe(cleanCss())
.pipe(rename({extname: '.min.css'}))
.pipe(dest('dist'))
}
自动化构建案例
样式编译
yarn add gulp --save
yarn add gulp-sass --dev
const {src, dest} = require('gulp')
const sass = require('gulp-sass')
const style = () =>{
return src('src/assets/styles/*.scss',{base:'src'})// base保存之前结构
.pipe(sass()) // 文件转换
.pipe(dest('dist'))
}
module.exports = {
style
}
脚本编译
ES6编译
yarn add gulp-babel --dev
yarn add @babel/core @babel/preset-env --dev es6整体转换
const babel = require('gulp-babel')
const script = () =>{
return src('src/assets/scripts/*.js',{base:'src'})
.pipe(babel({presets: ['@babel/preset-env']}))
.pipe(dest(dist))
}
module.exports = {
script
}
界面模板文件编译
yarn add gulp-swig --dev
const swig = require('gulp-swig')
const data = {
menu: [],
pkg: require('./package.json'),
date: new Date()
}
const page = () =>{
return src('src/*.html',{base:'src'})
.pipe(swig({data}))
.pipe(dest(dist))
}
module.exports = {
style,
script,
page
}
组合任务使用
const {src, dest, parallel} = require('gulp')
const sass = require('gulp-sass')
const style = () =>{
return src('src/assets/styles/*.scss',{base:'src'})// base保存之前结构
.pipe(sass()) // 文件转换
.pipe(dest('dist'))
}
const babel = require('gulp-babel')
const script = () =>{
return src('src/assets/scripts/*.js',{base:'src'})
.pipe(babel({presets: ['@babel/preset-env']}))
.pipe(dest(dist))
}
const swig = require('gulp-swig')
const data = {
menu: [],
pkg: require('./package.json'),
date: new Date()
}
const page = () =>{
return src('src/*.html',{base:'src'})
.pipe(swig({data}))
.pipe(dest(dist))
}
// 组合任务
const compile = parallel(style,script,page)
module.exports = {
compile
}
图片转换 字体转换
yarn add gulp-imagemin --dev
const imagemin = require('gulp-imagemin')
const image = () =>{
return src('src/assets/image/**',{base:'src'})
.pipe(imagemin()) // 图片压缩
.pipe(dest('dist'))
}
const font = () =>{
return src('src/assets/font/**',{base:'src'})
.pipe(imagemin())
.pipe(dest('dist'))
}
// 组合任务
const compile = parallel(style,script,page,image,font)
module.exports = {
compile,
}
额外文件
const extra = () =>{
return src('public/**', {base: 'public'})
.pipe(dest('dist'))
}
// 组合任务 src下
const compile = parallel(style,script,page,image,font)
// 其他文件
const build = parallel(compile,extra)
module.exports = {
build
}
清除dist重复文件
yarn add del --dev
const {src, dest, parallel, series} = require('gulp')
const del = require('del')
const clear = () =>{
return del(['dist'])
}
const build = series(clear, parallel(compile,extra))
自动加载插件
yarn add gulp-load-plugins --dev
const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()
开发服务器
热更新开发使用
yarn add browser-sync --dev
const browserSync = require(‘browser-sync’)
const bs = browserSync.create()
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: {
'/node_modules': 'node_modules'
}
}
})
}
处理引用代码及压缩完整代码
const { src, dest, parallel, series, watch } = require('gulp')
const del = require('del')
const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()
const browserSync = require('browser-sync')
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 = () => {
return del(['dist', 'temp'])
}
const style = () => {
return src('src/assets/styles/*.scss', { base: 'src' })
.pipe(plugins.sass({ outputStyle: 'expanded' }))
.pipe(dest('temp'))
.pipe(bs.reload({ stream: true }))
}
const script = () => {
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 = () => {
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/**',
server: {
baseDir: ['temp', 'src', 'public'],
routes: {
'/node_modules': 'node_modules'
}
}
})
}
const useref = () => {
return src('temp/*.html', { base: 'temp' })
.pipe(plugins.useref({ searchPath: ['temp', '.'] }))
// html js css 压缩
.pipe(plugins.if(/\.js$/, plugins.uglify()))
.pipe(plugins.if(/\.css$/, plugins.cleanCss()))
.pipe(plugins.if(/\.html$/, plugins.htmlmin({
collapseWhitespace: true,
minifyCSS: true,
minifyJS: true
})))
.pipe(dest('dist'))
}
const compile = parallel(style, script, page)
// 上线之前执行的任务
const build = series(
clean,
parallel(
series(compile, useref),
image,
font,
extra
)
)
const develop = series(compile, serve)
module.exports = {
clean,
build,
develop
}
package.json
"scripts": {
"clean": "gulp clean",
"build": "gulp build",
"develop": "gulp develop"
},
上一篇: ListView使用案例一之滑动冲突
下一篇: Gulp gulp学习使用