Mrcdh技术博客 Mrcdh技术博客
首页
  • Html5
  • Javascript
  • Nodejs
  • electron
  • Android
  • 微信公众号
  • 框架
  • 其他
  • Mysql
  • PHP
  • Python
  • java
  • Gulp
  • 其它
  • 网站
  • 资源
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

Mrcdh

全栈开发小学生
首页
  • Html5
  • Javascript
  • Nodejs
  • electron
  • Android
  • 微信公众号
  • 框架
  • 其他
  • Mysql
  • PHP
  • Python
  • java
  • Gulp
  • 其它
  • 网站
  • 资源
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • Mysql

  • PHP

  • Python

  • java

  • Go

  • 数据库

  • C#

  • ElasticSearch

  • Git

  • Gulp

    • gulp快速入门
    • JavaScript 和 Gulpfile
    • 使用 gulp 压缩 JS
      • 安装 gulp-uglify 模块(用于压缩 JS)
      • gulpfile.js 完整代码
      • 运行任务
      • 执行结果
      • 检测代码修改自动执行任务
      • 定义默认任务
    • 使用 gulp 压缩 CSS
    • 使用 gulp 处理 SASS
    • 使用 gulp 配置 tailwindcss + sass
  • Microsoft

  • Linux

  • 其它

  • 技术
  • Gulp
mrcdh
2021-02-02
目录

使用 gulp 压缩 JS

# 安装 gulp-uglify 模块(用于压缩 JS)

npm i gulp-uglify
1

# gulpfile.js 完整代码

const gulp = require('gulp');
const uglify = require('gulp-uglify');  // 该模块用于压缩js

// 压缩js任务
function compressJS(cb){
  // 1. 找到文件
  gulp.src('js/*.js')
    // 2. 压缩文件
    .pipe(uglify())
    // 3. 另存为压缩后的文件
    .pipe(gulp.dest('dist/js'))
  cb()
}

// 注册任务
exports.compressJS = compressJS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  • gulp.src(path) - 选择文件,传入参数是压缩的文件路径。API详情>>
  • gulp.dest(path) - 创建一个用于将 Vinyl 对象写入到文件系统的流。API详情>>
  • gulp.pipe() - 管道,你可以暂时将 pipe 理解为将操作加入执行队列。API详情>>

# 运行任务

gulp compressJS

[16:20:57] Using gulpfile D:\test\gulp\gulpfile.js
[16:20:57] Starting 'compressJS'...
[16:20:57] Finished 'compressJS' after 11 ms
1
2
3
4
5

# 执行结果

项目根路径
├── gulpfile.js
├──  js
│ └── main.js
├──  dist
│ └── js
│     └── main.js
└── node_modules
    └── gulp-uglify
1
2
3
4
5
6
7
8
9

# 检测代码修改自动执行任务

// 只有任务才能被执行,在任务中处理
function auto(cb){
    // 监听文件修改,当文件被修改时则执行 compressJS
    gulp.watch('js/*.js', compressJS)
    cb()
}

// 注册任务
exports.auto = auto
1
2
3
4
5
6
7
8
9
  • gulp.watch() - 监听文件被修改时触发任务。API详情>>

执行任务

gulp auto

[16:35:03] Using gulpfile D:\test\gulp\gulpfile.js
[16:35:03] Starting 'auto'...
[16:35:03] Finished 'auto' after 14 ms
1
2
3
4
5

控制台没有退出,当监听的文件修改保存后控制台将会出现提示,自动执行压缩任务

[16:35:30] Starting 'compressJS'...
[16:35:30] Finished 'compressJS' after 32 ms
1
2

使用ctrl + c停止 gulp。

# 定义默认任务

exports.default = auto
1
#gulp
上次更新: 2023/09/22, 16:54:32
JavaScript 和 Gulpfile
使用 gulp 压缩 CSS

← JavaScript 和 Gulpfile 使用 gulp 压缩 CSS→

最近更新
01
uniapp常见问题
03-19
02
Vue3项目搭建
12-25
03
使用pnpm的monorepo组织项目
11-01
更多文章>
Theme by Vdoing | Copyright © 2020-2025 Mrcdh | 苏ICP备2020058908号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×