本节记录一下 gulp 中常用的资源处理方式。
JS
js 文件的处理,主要是使用 babel 来进行转换,以及使用 uglify 来进行压缩。
分别安装 gulp-babel、gulp-uglify 及其他依赖项:
shell
yarn add gulp-babel @babel/core @babel/preset-env gulp-uglify -Djs
const { src, dest } = require('gulp')
const babel = require('gulp-babel')
const uglify = require('gulp-uglify')
function js() {
return src('js/*.js')
.pipe(babel({
presets: ['@babel/env']
}))
.pipe(uglify())
.pipe(dest('dist/js'))
}
exports.js = jsCSS
css 文件的处理,主要是使用 postcss 来进行转换,以及使用 clean-css 来进行压缩。
分别安装 gulp-postcss、gulp-clean-css :
shell
yarn add gulp-postcss gulp-clean-css -Djs
const { src, dest } = require('gulp')
const postcss = require('gulp-postcss')
const cleanCSS = require('gulp-clean-css')
function css() {
return src('styles/*.css')
.pipe(postcss())
.pipe(cleanCSS())
.pipe(dest('dist/css'))
}
exports.css = css为了使 postcss 起作用,需要在项目根目录下创建 .postcssrc.js 文件,内容如下:
js
module.exports = {
"plugins": {
// "postcss-import": {},
// "postcss-url": {},
// 浏览器兼容部分在package.json中
"autoprefixer": {}
}
}最后,还要创建 .browserslistrc 文件,内容如下:
> 1%
last 2 versions
not ie <= 8如果要对 less 、sass 等文件进行处理,可以使用 gulp-less、gulp-sass 等插件。
以 gulp-less 为例:
js
const { src, dest } = require('gulp')
const less = require('gulp-less')
const postcss = require('gulp-postcss')
const cleanCSS = require('gulp-clean-css')
const gulpIf = require('gulp-if')
function judgeCss(type) {
return file => file.extname.slice(1).toLowerCase() === type
}
function css() {
return src('styles/*.*')
// 此处判断文件类型,如果是less文件,则使用less插件进行处理
.pipe(gulpIf(judgeCss('less'), less()))
.pipe(postcss())
.pipe(cleanCSS())
.pipe(dest('dist/css'))
}
exports.css = cssHTML
html 文件的处理,主要是使用 gulp-htmlmin 来进行压缩。
安装 gulp-htmlmin :
shell
yarn add gulp-htmlmin -Djs
const { src, dest } = require('gulp')
const htmlmin = require('gulp-htmlmin')
function html() {
return src('*.html')
.pipe(htmlmin({
collapseWhitespace: true,
removeComments: true
}))
.pipe(dest('dist'))
}
exports.html = htmlImage
image 文件的处理,可以使用 gulp-smushit 来进行压缩。
安装 gulp-smushit :
shell
yarn add gulp-smushit -Djs
const { src, dest } = require('gulp')
const smushit = require('gulp-smushit')
function image() {
return src('images/*.{jpg,png}')
.pipe(smushit())
.pipe(dest('dist/images'))
}
exports.image = imageTIP
gulp-smushit 只能处理 jpg 和 png 格式的图片,如果要处理其他格式的图片,可以使用 gulp-imagemin 。
笔者在安装 gulp-imagemin 时,遇到了很多环境问题,故此处暂时以 gulp-smushit 为例。