【Node.js学习笔记】使用Gulp项目自动化构建工具

刚接触node.js,对前端的一些东西还不是很清楚,据说Gulp这东西很强大,先来看看从网上抄的一段关于自动化构建的描述:

  在为数众多的中小型软件作坊中,不存在自动化构建和发布工具。构建、交付准备环境、代码发布全由手工完成,同样还有运行测试、备份旧版本、新版本打标签以及许多其他重复的事情。毕竟你可能认为这全是非常简单的工作,集成开发环境通过按钮或快捷键就可构建项目,你开启两个窗口拖放少许文件或文件夹即可完成网站发布。但当你在维护代码库和应用时所有这些事情加在一起,这里几分钟,那里几分钟,最终会浪费几个小时。

后续:

经过本人最近一段时间的尝试和探索,发现Gulp的作用如下(纯个人观点,很可能误导):

1.重构正式运行的文件夹目录结构,因为有时候在开发时候的最优选择未必是发布时候的最优目录结构。

2.自动压缩CSS/JS

3.配合Browser-Sync这类的浏览器自动工具,还有一些测试工具,从而实现真正的自动化测试。

本人尝试Gulp的过程如下:

所用IDE:VS 2012 并安装node.js tools插件

1.新建一个Node.Js express 4项目,会给新建一个welcome的node.js程序。

2.通过npm引用相关包,我用到的包有:

gulp、del、run-sequence、gulp-jade、gulp-concat、gulp-uglify、gulp-rename

3.在原来新建好的welcome的项目基础上,我再public/javascripts下面新建了个js文件,叫test.js,内容随便写几行js。

4.根目录下新建个gulpfile.js,然后在cmd中cd到网站根目录下,或者直接右键点击项目,选择open command xxxx,然后敲个gulp(如果报错,先全局安装gulp再试)相信里面的注释已经比较清楚了。

 1 'use strict';
 2 var gulp=require('gulp');//引用类库,相当于.net中的using
 3 var plugins = {
 4     del: require('del'),
 5     runSequence: require('run-sequence'),
 6     jade: require('gulp-jade'),
 7     concat: require('gulp-concat'),
 8     uglify: require('gulp-uglify'),
 9     rename:require('gulp-rename')    
10 };
11 var jade = plugins.jade;
12 var concat = plugins.concat;
13 gulp.task('default', function (callback) {//default是入口
14     plugins.runSequence(
15         'task-clean',
16          ['task-script'], 
17          'task-jade',
18          callback
19     );
20 });
21 gulp.task('task-clean', function (callback) { 
22     plugins.del(['./dist/*.*'],callback());//清理dist文件夹中原来的东西
23 });
24 gulp.task('task-script', function () {
25     gulp.src('public/javascripts/*.js', { base:'public'})
26     .pipe(plugins.uglify())//js压缩
27     .pipe(plugins.rename({extname:'.min.js'}))//重命名
28     .pipe(gulp.dest('dist'));//输出到dist目录
29 });
30 var watcher= gulp.watch('public/javascripts/*.js', ['task-script']);//监控这个文件夹,有变化了运行task-script task
31 watcher.on('change', function (e) {
32     console.log('File ' + e.path + ' was ' + e.type + ', running tasks...');//变化了之后控制台打印一下,方便调试
33 });

 ===========后续,文件更改自动刷新浏览器=====================

5.既然文件都变了,那肯定要重置当前的浏览器状态,让他自己来刷新,免得我们每次都得手动去做这件事情,这时候我们就需要引入Browser-Sync,直接贴代码比较清晰一点

 1 //构建Gulp Task,用来启动一个mini Server,Host你的网站
 2 gulp.task('browser-sync', function () {
 3     plugins.browserSync.init({
 4         server: {
 5             baseDir: './dist'
 6         },       
 7         port: 8888       
 8     })
 9 });
10 //gulp task:刷新浏览器
11 gulp.task('bs-reload', function () {
12     plugins.browserSync.reload();
13     console.log("模块重新构建成功".green);
14 });
15 var watcher = gulp.watch(
16     ['public/javascripts/*.js','index.html'],
17      ['task-script', 'task-index', 'bs-reload']);//监控这个文件夹,有变化了运行task,最后刷浏览器

6.JS/CSS加上时间戳,防止因为浏览器缓存造成的各种操蛋的问题。

//在构建Html的时候,去给Html中的引用加上版本号,而不是在构建JS的时候,我犯过这错误
gulp.task('task-index', function () {
    var version = (new Date).valueOf() + '';
    gulp.src('index.html')
    .pipe(plugins.replace('.js"></script>', '.min.js?v=' + version + '"></script>'))
    .pipe(gulp.dest('dist'));
    console.log('task-index 构建成功'.green);
});

 7. 参数化构建,把一些东西写到配置里面,优化一把

var gulp=require('gulp');
var del=require('del');
var runSequence=require('run-sequence');
var concat=require('gulp-concat');
var uglify=require('gulp-uglify');
var rename=require('gulp-rename');
var colors=require('colors');
var browserSync=require('browser-sync').create();
var appConfig={
    appPath:require("./browser.json").appPath||'src', //配置源文件路径
    dist:'dist',//配置打包路径
    isDebug:true//配置编译方式
};
var assets= appConfig.appPath+'/assets/';
var watchPath={
    scripts:[assets+'scripts/**/*.js'],
    styles:[assets+'styles/**/*.css'],
    plugins:[assets+'plugins/**/*.*'],
    images:[assets+'images/**/*.*']
};
gulp.task('main',function(){
    runSequence();
});
gulp.task('clean',function(callback){
    del([appConfig.dist+'/*.*'],callback);
});
gulp.task('scripts',function(){
    var gulpStream=gulp.src(watchPath.scripts,{base:appConfig.appPath});
    if(appConfig.isDebug){
        gulpStream=gulpStream.pipe(uglify());
    }
    return gulpStream.pipe(gulp.dest(appConfig.dist));
    console.log('scripts bulid complete'.green);
});

 8.Bower自动添加引用到首页。

gulp.task('bower', function () {
  return gulp.src([paths.views.main])
    .pipe(wiredep({
      directory: 'bower_components',
      //exclude: [],
      //ignorePath: '/^(../)*../'
      ignorePath: '..'
    }))
    .pipe(gulp.dest('app'));
});

 9.模块化构建项目,自动刷新浏览器

var gulp=require('gulp');
var del=require('del');
var runSequence=require('run-sequence');
var concat=require('gulp-concat');
var uglify=require('gulp-uglify');
var rename=require('gulp-rename');
var colors=require('colors');
var cssnano = require('gulp-cssnano');
var browserSync=require('browser-sync').create();
var wiredep=require("wiredep").stream;
var mainBowerFiles = require('main-bower-files');
var appConfig={
    appPath:require("./bower.json").appPath||'src', //配置源文件路径
    dist:'dist/',//配置打包路径
    isDebug:true//配置编译方式
};
var assets= appConfig.appPath+'/assets';
var bowerPath=assets+"/plugins";
var watchPath={
    scripts:[assets+'/scripts/**/*.js'],
    styles:[assets+'/styles/**/*.css'],
    plugins:[assets+'/plugins/**/*.*'],
    images:[assets+'/images/**/*.*'],
    main:appConfig.appPath+'/index.html',
    views:appConfig.appPath+'/views/**/*.html',
    js:appConfig.appPath+'/js/**/*.js',
    theme:appConfig.appPath+'/theme/**/*.html'
};
gulp.watch(watchPath.scripts,['scripts','reload']);
gulp.watch(watchPath.styles,['styles','reload']);
gulp.watch(watchPath.plugins,['plugins','reload']);
gulp.watch(watchPath.images,['images','reload']);
gulp.watch('./bower.json',['bower','main-bower-files','reload']);
gulp.watch([watchPath.views,watchPath.main],['views','reload']);
gulp.watch(watchPath.js,['js','reload']);
gulp.watch(watchPath.theme,['theme','reload']);

gulp.task('clean',function(){
    del([appConfig.dist+'/*.*']);
    console.log('clean task complete!'.green);
});
gulp.task('scripts',function(){
    var gulpStream=gulp.src(watchPath.scripts,{base:appConfig.appPath});
    if(!appConfig.isDebug){
        gulpStream=gulpStream.pipe(uglify());
    }
    console.log('scripts bulid complete'.green);
    return gulpStream.pipe(gulp.dest(appConfig.dist));    
});
gulp.task('styles',function(){
    var gulpStream=gulp.src(watchPath.styles,{base:appConfig.appPath});
    if(!appConfig.isDebug){
        gulpStream=gulpStream.pipe(cssnano());
    }
    console.log('styles bulid complete'.green);
    return gulpStream.pipe(gulp.dest(appConfig.dist));
});
gulp.task('bower', function () {
  return gulp.src([watchPath.main])
    .pipe(wiredep({
      directory: bowerPath,
      //exclude: [],
      //ignorePath: '/^(../)*../'
    }))
    .pipe(gulp.dest(appConfig.appPath));
});
gulp.task('js',function(){
    gulp.src(watchPath.js,{base:appConfig.appPath})
    .pipe(gulp.dest(appConfig.dist));
});
gulp.task('theme',function(){
    gulp.src(watchPath.theme,{base:appConfig.appPath})
    .pipe(gulp.dest(appConfig.dist));
});
gulp.task('views',['bower'],function(){
    gulp.src([watchPath.views,watchPath.main],{base:appConfig.appPath})
    .pipe(gulp.dest(appConfig.dist));
    console.log('Html bulid complete'.green);
});
gulp.task("main-bower-files", function(){
    return gulp.src(mainBowerFiles(), { base: appConfig.appPath })
        .pipe(gulp.dest(appConfig.dist));
});
gulp.task('images',function(){
    gulp.src(watchPath.images,{base:appConfig.appPath})
    .pipe(gulp.dest(appConfig.dist));
});
gulp.task('reload', function () {
    browserSync.reload();
    console.log("模块重新构建成功".green);
});

gulp.task('serve', ['clean','views','theme','images', 'js','styles', 'scripts','main-bower-files'], function() {
 console.log('Build Complate!Server Strarting......');
 browserSync.init({
        server: {
            baseDir: './dist'
        },       
        port: 8888
    })
});

gulp.task('default', ['serve']);
原文地址:https://www.cnblogs.com/baiyunchen/p/5152993.html