使用gulp打包html+jquery项目
发布时间 2024-06-12 21:11:59

前言

  最近在做了一个 html+jquery 官方网站项目,打算用 gulp 对当前多页面项目进行打包,记录一下过程。

使用 gulp

  下面给一个示例,具体的配置还需要根据自己的项目进行调整,还有里面用到的插件,比如 gulp-htmlmin、gulp-uglify、gulp-clean-css 等自行安装。

  • gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const { src, dest, series, parallel } = require('gulp')
// const rename = require('gulp-rename')

const cleanCSS = require('gulp-clean-css')

const uglify = require('gulp-uglify')
const babel = require('gulp-babel')

const htmlmin = require('gulp-htmlmin')

// ========= Compress task ===========

const compressCSS = () => {
return (
src('src/css/*.css')
.pipe(cleanCSS())
// .pipe(rename({ suffix: '.min' }))
.pipe(dest('dist/css'))
)
}

const compressJS = () => {
return (
src('src/js/*.js')
.pipe(
babel({
presets: ['@babel/env']
})
)
.pipe(uglify())
// .pipe(rename({ suffix: '.min' }))
.pipe(dest('dist/js'))
)
}

const compressHTML = () => {
return src('src/**/*.html')
.pipe(
htmlmin({
removeComments: true,
minifyCSS: true,
minifyJS: true,
collapseWhitespace: true
})
)
.pipe(dest('dist'))
}

// ========= Static task ===========

const compressLib = () => {
return src('src/lib/**/*').pipe(dest('dist/lib'))
}

const compressImages = () => {
return src('src/image/**/*', { encoding: false }).pipe(dest('dist/image'))
}

// ========= Clean task ===========

const clean = () => {
return src('dist', { read: false, allowEmpty: true }).pipe(require('gulp-clean')({ force: true }))
}

exports.clean = clean

exports.build = series(
clean,
parallel(compressCSS, compressJS, compressHTML),
parallel(compressLib, compressImages)
)
  • package.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
// ……
"scripts": {
"build": "gulp build",
"clean": "gulp clean"
},
"devDependencies": {
"@babel/core": "^7.24.7",
"@babel/preset-env": "^7.24.7",
"gulp": "^5.0.0",
"gulp-babel": "^8.0.0",
"gulp-clean": "^0.4.0",
"gulp-clean-css": "^4.3.0",
"gulp-htmlmin": "^5.0.1",
"gulp-rename": "^2.0.0",
"gulp-uglify": "^3.0.2"
}
// ……
}

注意事项

1、gulp 版本问题

  上述案例中,我直接使用的是最新的 gulp 版本(gulp 5.0.0),写法上直接参考的官方网站示例,可能与 gulp v4 及之前版本写法上有些许差别,具体请根据自己的项目情况进行调整。

2、gulp 打包后图片损坏问题

  对于这个问题,在上面示例中可以直接看到我额外的添加了配置:{ encoding: false },具体可以查看这条 issue:issue#2803

拓展阅读

  其实我们还可以对 image 图片进行了 gulp-imagemin 处理,但在 M1 电脑上使用 gulp-imagemin 可能会遇到一些问题,并且 gulp-imagemin 采用的是无损压缩,图片大小并不会减少多少。

  因此如果不是刚需,个人感觉没必要使用 gulp-imagemin。下面是个人踩坑记录:

1、gulp-imagemin 安装失败问题

  这个问题网上清一色的是使用 cnpm,但我对 cnpm 使用非常反感,因此在 github 看到了如下解决方案:issue#8

2、打包 build 报错问题 1

  另外,在我的 M1 电脑上使用最新的版本时,进行 build 操作时会发生报错:require() of ES modules is not supported,解决方案可以查看 issue#372

3、打包 build 报错问题 2

  并且后续还可能包另一个错误:Couldn't load default plugin "opting",解决方案可以查看 issue#353

上一页
2024-06-25 17:51:14
下一页