In this section, we learn how to use gulp
compress JS
. In actual projects, if the JS
file is too large, it may cause the page load to slow down. So we can JS
files. In addition to choosing to use various tools to manually compress, we can also compress JS
files gulp
Compress JS files
To use gulp
to compress JS
files, a gulp-uglify
plug-in is needed. Let's take a look at how to compress JS
files.
For example, we are working to achieve compression js
all directory .js
files, these JS
compressed file to dist
directory js
folder.
Install plugin
First, we need to install the gulp-uglify
plug-in, open the command line tool, or directly open the terminal VSCode
And then proceeds to gulpfile.js
directory files are located, if your project has not been this file, you will need to create this file yo, because gulp
all configuration codes are written in gulpfile.js
file. .
As shown in the figure below, execute the command to gulp-uglify
npm install gulp-uglify
Write the code in the gulpfile.js file
After the plug-in is installed successfully, we can write the code gulpfile.js
gulp
module:
// 获取 gulp
var gulp = require('gulp')
Then get the uglify
module:
var uglify = require('gulp-uglify')
Then you can create a compression task task()
gulp.task('script', function() {
// 找到要压缩的js文件
gulp.src('js/*.js')
// 压缩文件
.pipe(uglify())
// 将压缩后的文件存到只指定目录
.pipe(gulp.dest('dist/js'))
})
Execute compression command
Then we can execute the gulp script
command in the command line tool, where script
is the task name.
dist
directory will be automatically generated under the project root directory, and the specified JS
file has been successfully compressed into the js
folder under this directory.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。