漂泊雪狼的博客

思考,讨论,分享C#,JavaScript,.NET,Oracle,SQL Server……技术

导航

使用gulp压缩js详细步骤笔记

Posted on 2017-04-29 22:27  漂泊雪狼  阅读(780)  评论(0编辑  收藏  举报

先要安装nodejs,初始化项目配置文件package.json,根据情况输入配置参数

npm init
 1 test command:
 2 git repository:
 3 keywords:
 4 author:
 5 license: (ISC)
 6 About to write to E:\temp\20170429\test03\package.json:
 7 
 8 {
 9   "name": "test03",
10   "version": "1.0.0",
11   "description": "",
12   "main": "index.js",
13   "scripts": {
14     "test": "echo \"Error: no test specified\" && exit 1"
15   },
16   "author": "",
17   "license": "ISC"
18 }
npm init

 

安装gulp

npm install gulp -g   (global环境)

npm install gulp --save-dev (项目环境)

在项目中install需要的gulp插件,一般只压缩的话需要npm install gulp-minify-css gulp-concat gulp-uglify gulp-rename del --save-dev更多插件可以在这个链接中找到 http://gratimax.net/search-gulp-plugins/

 

在项目的根目录新建gulpfile.js,require需要的module

var gulp = require('gulp'),    
   uglify = require('gulp-uglify');  
   

    gulp.task("default",function()
    {
        gulp.src("src/*.js").pipe(uglify()).pipe(gulp.dest("dist/js"));
    })

执行gulp命令进行js压缩

E:\temp\20170429\test03>gulp
[22:23:05] Using gulpfile E:\temp\20170429\test03\gulpfile.js
[22:23:05] Starting 'default'...
[22:23:05] Finished 'default' after 13 ms

 监控文件修改自动执行任务

 1 gulp.task("file_change",function()
 2     {
 3        gulp.src("src/*.js").pipe(uglify()).pipe(gulp.dest("dist/js"));
 4         console.log("uglifyed");
 5     })
 6 
 7 
 8     gulp.task("auto",function()
 9     {
10         gulp.watch("src/*.js",["file_change"]);
11     })

执行gulp auto,文件修改是自动执行压缩任务

E:\temp\20170429\test03>gulp auto
[23:35:46] Using gulpfile E:\temp\20170429\test03\gulpfile.js
[23:35:46] Starting 'auto'...
[23:35:46] Finished 'auto' after 13 ms
[23:35:51] Starting 'file_change'...
uglifyed
[23:35:51] Finished 'file_change' after 18 ms
[23:35:53] Starting 'file_change'...
uglifyed
[23:35:53] Finished 'file_change' after 4.75 ms
[23:36:04] Starting 'file_change'...
uglifyed