使用:
项目创建gulpfile.js文件
以模块导出的形式暴露gulp相应任务操作
常用gulp插件
src、dest用于创建gulp输入输出文件流
series、parallel用于创建gulp串形和并行任务
// 实现这个项目的构建任务
const { src, dest, series, parallel, watch } = require('gulp');
// 自动加载插件
const loadPlugins = require('gulp-load-plugins');
const plugins = loadPlugins();
// 在线运行插件
const browsersync = require('browser-sync');
const bs = browsersync.create();
// 清空文件目录插件
const del = require('del')
const clean = () => {
return del(['temp', 'dist'])
}
// html文件构建
const pages = () => {
return src('src/*.html', { base: 'src' })
.pipe(plugins.swig({defaults: { cache: false }}))
.pipe(dest('temp'))
.pipe(bs.reload({ stream: true }))
}
// css文件构建
const style = () => {
return src('src/assets/styles/*.scss', { base: 'src' })
.pipe(plugins.sass({ outputStyle: 'expanded' }))
.pipe(dest('temp'))
.pipe(bs.reload({ stream: true }))
}
// js文件构建
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 images = () => {
return src('src/assets/images/**', { base: 'src' })
.pipe(plugins.imagemin())
.pipe(dest('dist'))
}
// 字体文件构建
const fonts = () => {
return src('src/assets/fonts/**', { base: 'src' })
.pipe(plugins.imagemin())
.pipe(dest('dist'))
}
// 其他类型文件构建
const pubs = () => {
return src('public/**', { base: 'public' })
.pipe(dest('dist'))
}
// html、js、css文件压缩,node_modules模块打包
const useref = () => {
return src('temp/*.html', { base: 'temp' })
.pipe(plugins.useref({ searchPath: ['temp', '.'] }))
.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 serve = () => {
watch('src/*.html', pages)
watch('src/assets/styles/*.scss', style)
watch('src/assets/scripts/*.js', script)
watch([
'src/assets/images/**',
'src/assets/fonts/**',
'public/**',
], bs.reload)
bs.init({
notify: false,
port: 8084,
open: true,
server: {
baseDir: ['temp', 'src', 'public'],
routes: {
'/node_modules': 'node_modules'
}
}
})
}
// 并行执行html,css,js文件构建任务(抽离字体、图片内容,这些内容仅在build打包时编译即可)
const compile = parallel(pages, style, script);
// 项目整体构建
const build = series(clean, parallel(series(compile, useref), fonts, images, pubs))
// 运行
const dev = series(compile, serve)
module.exports = {
script,
style,
pages,
images,
fonts,
pubs,
clean,
compile,
build,
dev,
}