gulp初体验
项目流程
安装nodejs -> 全局安装gulp -> 项目安装gulp以及gulp插件 -> 配置gulpfile.js -> 运行任务
常用命令简介:
node -v 查看node版本
npm -v 查看npm版本
cd 定位到目录,用法:cd + 路径 ;
dir 列出文件列表;
cls 清空命令提示符窗口内容
安装包
npm install <name> [-g] [--save-dev]
-g:全局安装。将会安装在C:\Users\Administrator\AppData\Roaming\npm,并且写入系统环境变量; 非全局安装:将会安装在当前定位目录; 全局安装可以通过命令行在任何地方调用它,本地安装将安装在定位目录的node_modules文件夹下,通过require()调用;
--save:将保存配置信息至package.json(package.json是nodejs项目配置文件);
-dev:保存至package.json的devDependencies节点,不指定-dev将保存至dependencies节点;
为什么要保存至package.json?因为node插件包相对来说非常庞大,所以不加入版本管理,将配置信息写入package.json并将其加入版本管理,其他开发者对应下载即可(命令提示符执行npm install,则会根据package.json下载所有需要的包)。
安装指定版本包
npm install -g npm@3.5
更新插件
npm update <name> [-g] [--save-dev]
删除插件
npm uninstall <name> [-g] [--save-dev]
生成package.json
npm init
安装本地插件
npm install [name] --save-dev
以下为测试“gulp-livereload”浏览器自动刷新代码:
谷歌浏览器或火狐安装livereload插件(必须此插件方能生效)
安装方法:谷歌浏览器安装crx插件方法、火狐浏览器直接将xpi文件拖进浏览器即可安装。点击下载(谷歌为.crx文件,火狐为.xpi文件)
注:安装方法在chrome测试通过,firefox安装时提示未通过验证,不支持IE。
package.json
1 { 2 "name": "myapp", 3 "version": "1.0.0", 4 "description": "", 5 "main": "index.js", 6 "scripts": { 7 "test": "echo \"Error: no test specified\" && exit 1" 8 }, 9 "author": "", 10 "license": "ISC", 11 "devDependencies": { 12 "gulp": "^3.9.1", 13 "gulp-livereload": "^3.8.1" 14 } 15 }
gulpfile.js
1 // 监听all变化 2 var gulp = require('gulp'), //本地安装gulp所用到的地方 3 livereload = require('gulp-livereload'); 4 gulp.task('All', function() { 5 gulp.src('src/**') 6 .pipe(livereload()); 7 }); 8 gulp.task('watchAll', function() { 9 livereload.listen(); 10 gulp.watch('src/**', ['All']); 11 }); 12 //gulp.task(name[, deps], fn) 定义任务 name:任务名称 deps:依赖任务名称 fn:回调函数 13 //gulp.src(globs[, options]) 执行任务处理的文件 globs:处理的文件路径(字符串或者字符串数组) 14 //gulp.dest(path[, options]) 处理完后文件生成路径
cd到当前目录,执行命令“gunp watchAll”。
运行项目http://localhost/....,注意,必须使用http[s]协议,file协议不生效。
当修改src目录里面文件时,浏览器会自动刷新。
现项目中使用的gulpfile.js
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 var gulp = require("gulp") 2 , gutil = require("gulp-util") 3 4 , del = require("del") 5 , sass = require("gulp-sass") 6 , uglify = require('gulp-uglify') 7 , rename = require("gulp-rename") 8 9 , browserSync = require("browser-sync").create() 10 , reload = browserSync.reload 11 12 , sequence = require("run-sequence") 13 , plumber = require("gulp-plumber") 14 , watch = require("gulp-watch") 15 16 , through2 = require("through2") 17 , path = require("path") 18 , fs = require("fs"); 19 20 21 // ############################################# 22 // # init params 23 24 // 收集参数 25 var cwd = process.cwd(); 26 var cmdargs = process.argv.slice(2); 27 var cmdname = cmdargs.shift(); 28 var cmdopts = {}; 29 var srcpath = "./src"; 30 var distpath = "./dist"; 31 32 while (cmdargs.length) { 33 var key = cmdargs.shift().slice(2); 34 var val = cmdargs.shift(); 35 cmdopts[key] = key === "src" || key === "dist" ? normalizePath(val) : val; 36 } 37 38 // 参数配置 39 var release = cmdname === "release"; 40 var reloadTimer = null; 41 var devport = 5678; 42 var paths = { 43 src: path.join(__dirname, srcpath), 44 dist: path.join(__dirname, distpath) 45 } 46 47 function normalizePath(url) { 48 if (url.charAt(0) === "/" || url.indexOf(":") > -1) { 49 return path.normalize(url); 50 } 51 return path.normalize(path.join(cwd, url)); 52 } 53 54 function setOptions(cmd, cmdopts) { 55 if (cmd === "start") { 56 paths.src = cmdopts.src ? path.join(cmdopts.src, srcpath) : paths.src; 57 } else if (cmd === "release") { 58 paths.src = cmdopts.src ? path.join(cmdopts.src, srcpath) : paths.src; 59 paths.dist = cmdopts.dist ? cmdopts.dist : path.normalize(paths.src + "/../" + distpath); 60 } 61 } 62 63 function showUsage() { 64 console.log("Usage:\n"); 65 console.log(" gulp 显示帮助"); 66 console.log(" gulp help 显示帮助"); 67 console.log(" gulp start --src src 在--src目录下自动化开发调试环境"); 68 console.log(" gulp release --src src --dist dist 构建--src线上版本到--dist目录\n"); 69 console.log(" gulp start --src src --proxy localhost 使用gulp代理localhost请求,并且实时监听src文件修改"); 70 } 71 72 // ############################################# 73 // # default tasks 74 75 // # clean path 76 gulp.task("clean:dist", function () { 77 return del([paths.dist], {force: true}); 78 }); 79 80 // # 编译css 81 gulp.task("sass", function() { 82 var base = paths.src; 83 var dest = base; 84 return gulp.src(base + "/**/*.scss", {base: base}) 85 .pipe(plumber()) 86 .pipe(sass({ 87 precision: 2, 88 outputStyle: release ? "compressed" : "expanded" 89 //sourceComments: release ? false : true 90 }) 91 .on("error", sass.logError)) 92 .pipe(gulp.dest(dest)); 93 }); 94 95 96 // # 压缩js 97 gulp.task("uglify", function() { 98 var base = paths.src; 99 var dest = paths.dist; 100 return gulp.src(base + "/**/*.js", {base: base}) 101 .pipe(plumber()) 102 .pipe(uglify()) 103 .pipe(gulp.dest(dest)); 104 }); 105 106 // # 复制静态资源 107 gulp.task("copy:dist", function() { 108 var base = paths.src; 109 var dest = paths.dist; 110 return gulp.src([ 111 base + "/**/*", 112 "!" + base + "/**/*.js", 113 "!" + base + "/**/*.scss" 114 ], {base: base}) 115 .pipe(gulp.dest(dest)); 116 }); 117 118 119 // # serv & watch 120 gulp.task("server", function() { 121 // start server 122 browserSync.init({ 123 ui: false, 124 notify: false, 125 port: devport, 126 // 设置代理请求 127 proxy: cmdopts.proxy, 128 server: !cmdopts.proxy ? { 129 baseDir: paths.src 130 } : false 131 }); 132 133 // # watch src资源, 调用相关任务预处理 134 watch(paths.src + "/**/*.scss", function(obj) { 135 sequence("sass"); 136 }); 137 138 // # 刷新浏览器 139 // # 限制浏览器刷新频率 140 watch(paths.src + "/**/*", function(obj) { 141 var url = obj.path.replace(/\\/g, "/"); 142 var absurl = url; 143 url = path.relative(paths.src, url); 144 console.log("[KS] " + absurl); 145 146 // skip scss 147 if (!/\.scss$/.test(url)) { 148 if (reloadTimer) { 149 clearTimeout(reloadTimer); 150 } 151 reloadTimer = setTimeout(reload, 1000); 152 } 153 }); 154 }); 155 156 157 // ############################################# 158 // # public task 159 160 gulp.task("default", showUsage); 161 gulp.task("help", showUsage); 162 163 gulp.task("start", function(cb) { 164 release = false; 165 setOptions("start", cmdopts); 166 sequence("sass", "server", cb); 167 }); 168 169 gulp.task("release", function(cb) { 170 release = true; 171 setOptions("release", cmdopts); 172 sequence("clean:dist", ["sass", "uglify"], "copy:dist", cb); 173 });
package.json
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 { 2 "name": "work", 3 "version": "1.0.0", 4 "description": "", 5 "main": "index.js", 6 "scripts": { 7 "test": "echo \"Error: no test specified\" && exit 1" 8 }, 9 "author": "", 10 "license": "ISC", 11 "devDependencies": { 12 "autoprefixer": "^6.3.6", 13 "autoprefixer-core": "^6.0.1", 14 "browser-sync": "^2.13.0", 15 "cssgrace": "^3.0.0", 16 "cssnext": "^1.8.4", 17 "del": "^2.2.1", 18 "fs": "^0.0.2", 19 "gulp": "^3.9.1", 20 "gulp-concat": "^2.6.0", 21 "gulp-htmlmin": "^2.0.0", 22 "gulp-imagemin": "^3.0.1", 23 "gulp-jshint": "^2.0.1", 24 "gulp-less": "^3.1.0", 25 "gulp-livereload": "^3.8.1", 26 "gulp-minify-css": "^1.2.4", 27 "gulp-notify": "^2.2.0", 28 "gulp-plumber": "^1.1.0", 29 "gulp-postcss": "^6.1.1", 30 "gulp-rename": "^1.2.2", 31 "gulp-sass": "^2.3.2", 32 "gulp-uglify": "^1.5.3", 33 "gulp-util": "^3.0.7", 34 "gulp-watch": "^4.3.8", 35 "imagemin-jpegtran": "^5.0.2", 36 "imagemin-pngcrush": "^5.0.0", 37 "jshint": "^2.9.2", 38 "path": "^0.12.7", 39 "run-sequence": "^1.2.1", 40 "through2": "^2.0.1" 41 } 42 }