Skip to content

本节记录一下 gulp 中常用的资源处理方式。

JS

js 文件的处理,主要是使用 babel 来进行转换,以及使用 uglify 来进行压缩。

分别安装 gulp-babelgulp-uglify 及其他依赖项:

shell
yarn add gulp-babel @babel/core @babel/preset-env gulp-uglify -D
js
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 = js

CSS

css 文件的处理,主要是使用 postcss 来进行转换,以及使用 clean-css 来进行压缩。

分别安装 gulp-postcssgulp-clean-css

shell
yarn add gulp-postcss gulp-clean-css -D
js
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

如果要对 lesssass 等文件进行处理,可以使用 gulp-lessgulp-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 = css

HTML

html 文件的处理,主要是使用 gulp-htmlmin 来进行压缩。

安装 gulp-htmlmin

shell
yarn add gulp-htmlmin -D
js
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 = html

Image

image 文件的处理,可以使用 gulp-smushit 来进行压缩。

安装 gulp-smushit

shell
yarn add gulp-smushit -D
js
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 = image

TIP

gulp-smushit 只能处理 jpgpng 格式的图片,如果要处理其他格式的图片,可以使用 gulp-imagemin

笔者在安装 gulp-imagemin 时,遇到了很多环境问题,故此处暂时以 gulp-smushit 为例。