美文网首页我爱编程
前端构建工具 Gulp 的使用总结

前端构建工具 Gulp 的使用总结

作者: 嗨超儿 | 来源:发表于2018-05-27 21:00 被阅读17次

目录

  • why
  • 环境搭建
  • gulp
  • gulpfile.js文件解析
  • 开发部署流程

1.why

  • 自动清除缓存,自动刷新,加速开发调试过程 browserSync or browserSync国内

  • js代码压缩,节省带宽。

  • css文件,加入hash码,方便测试。(已知情况,js修改不用清缓存,css文件需要)

2.环境搭建

windows环境node安装,
可以参考该教程,Linux系统可以参考,
教程一,
教程二

注意事项

如果node下载速度过慢,可以考虑使用国内的node下载站

3.gulp

中文官网

入门指南
  • 全局安装 gulp:
$ npm install --global gulp
  • 作为项目的开发依赖(devDependencies)安装:
$ npm install --save-dev gulp
  • 在项目根目录下创建一个名为 gulpfile.js 的文件:
var gulp = require('gulp');
gulp.task('default', function() {
  // 将你的默认的任务代码放在这
});
  • 运行 gulp:
$ gulp

4.gulpfile.js文件解析

let gulp = require('gulp'),

    // html相关
    htmlmin = require('gulp-htmlmin'), // 去掉html注释

    // css相关
    cleanCss = require('gulp-clean-css'),  // 压缩css

    // js相关
    uglify = require('gulp-uglify'),  // 压缩js
    babel = require('gulp-babel'),    // es6转码
    eslint = require('gulp-eslint'),  // 脚本检查

    // 判断文件是否修改
    changed = require('gulp-changed'),

    // 发生错误后继续进程
    plumber = require('gulp-plumber'),

    // 调试
    debug = require('gulp-debug'), // 打印经过pipe的文件名

    // 日志添加颜色
    chalk = require('chalk'),
    log = console.log,   // 打印

    // 删除文件
    del = require('del'), // 删除旧版本文件

    // 任务执行顺序
    runSequence = require('gulp-sequence'), // 串行任务

    // 服务器
    browserSync = require('browser-sync').create(), // -创建服务器

    //在pipe中使用if判断条件
    gulpif = require('gulp-if'),

    //命令行替换变量
    minimist = require('minimist'),

    // css添加版本号
    rev = require('gulp-rev'),  // 添加MD5后缀
    revCollector = require('gulp-rev-collector');  // 路径替换
    
// Environment setup 环境设置
/*
 * env----代表环境变量
 * 启动gulp命令的几种方式
 * gulp----执行默认操作(gulp --env 0)
 * 开发时直接执行gulp命令就行
 *
 * gulp --env 0-----开发
 *
 * 执行gulp则默认执行  gulp --env 0
 */


let knownOptions = {
    string: 'env',
    default: {env: process.env.NODE_ENV || '0'}
};

let options = minimist(process.argv.slice(2), knownOptions);


//web本地服务器配置
let host = {
    path: 'src/main/app/',   // 文件输出目录即开发目录
    build: 'src/main/webapp/',  // 项目构建目录
};

gulp.task('serve', () => {
    browserSync.init({
        proxy: 'http://192.168.0.103:8080',
        serveStatic: [host.path],
        browser: ['chrome'],
        files: [
            `${host.path}**/*.html`,
            `${host.path}**/*.css`,
            `${host.path}**/*.js`,
            `${host.path}img/!**/!*.*`
        ],
    });
});

// 代码检查
gulp.task('lint', () => {
    return gulp.src([host.path + 'js/**/*.js'])
        .pipe(eslint({
            configFile: '.eslintrc.js',
        }))
        .pipe(eslint.formatEach())
        .pipe(eslint.results(results => {
            log(chalk.gray(`Total Files: ${results.length}`));
            log(chalk.redBright(`Total Errors: ${results.errorCount}`));
            log(chalk.yellow(`Total Warnings: ${results.warningCount}`));
        }))
});

// 代码修复
const isFixed = (file) => {
    return file.eslint !== null && file.eslint.fixed;
};

gulp.task('lint-fix', () => {
    return gulp.src([host.path + 'js/**/*.js'])
        .pipe(eslint({
            fix: true,
        }))
        .pipe(gulpif(isFixed, gulp.dest(host.path + 'js')));
});

// 压缩html
let htmlOptions = {
    removeComments: true,   // 清除注释
    collapseWhitespace: true,  // 压缩html
    removeEmptyAttributes: false, // 删除所有空格作属性值 <input id="" /> ==> <input />
    removeScriptTypeAttributes: false, // 删除<script>的type="text/javascript"
    minifyJS: true, // 压缩页面JS
    minifyCSS: true, // 压缩页面css
};

gulp.task('html', () => {
    return gulp.src(host.path + '**/*.html')
        .pipe(plumber())
        .pipe(changed(host.build))
        .pipe(debug({title: '编译:'}))
        .pipe(htmlmin(htmlOptions))
        .pipe(gulp.dest(host.build))
});

// 压缩css + 添加版本号
gulp.task('mincss', () => {
    return gulp.src(host.path + 'css/*.*')
        .pipe(plumber())
        .pipe(debug({title: '编译:'}))
        .pipe(cleanCss())   //- 压缩处理成一行
        .pipe(rev())    //- 文件名加MD5后缀
        .pipe(gulp.dest(host.build + 'css'))  //- 输出文件本地
        .pipe(rev.manifest())   //- 生成一个rev-manifest.json
        .pipe(gulp.dest(host.build + 'css'));  //- 将 rev-manifest.json 保存到 rev 目录内
});
// 替换css路径
gulp.task('revcss', () => {
    return gulp.src([host.build + 'css/*.json', host.build + '**/*.html']) //- 读取 rev-manifest.json 文件以及需要进行css名替换的文件
        .pipe(revCollector())   //- 执行文件内css名的替换
        .pipe(gulp.dest(host.build));  //- 替换后的文件输出的目录
});
gulp.task('css', (cb) => runSequence(['mincss'], ['revcss'])(cb));

// js转码
gulp.task('babel', () => {
    return gulp.src(host.path + '**/*.js')
        .pipe(plumber())
        .pipe(changed(host.build + 'js'))
        .pipe(debug({title: '编译:'}))
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(gulp.dest(host.build + 'js'))
});

// js压缩
gulp.task('js', () => {
    return gulp.src(host.path + 'js/**/*.js')
        .pipe(plumber())
        .pipe(changed(host.build + 'js'))
        .pipe(debug({title: '编译:'}))
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(uglify())
        .pipe(gulp.dest(host.build + 'js'))
});

// configjs转化压缩
gulp.task('configjs', () => {
    return gulp.src(host.path + 'config.js')
        .pipe(plumber())
        .pipe(changed(host.build))
        .pipe(debug({title: '编译:'}))
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(uglify())
        .pipe(gulp.dest(host.build))
});

gulp.task('pageJs', (cb) => runSequence(['js'], ['configjs'])(cb));

// static库文件处理
gulp.task('static', function () {
    return gulp.src(host.path + 'static/**/*')
        .pipe(plumber())
        .pipe(changed(host.build + 'static'))
        .pipe(debug({title: '编译:'}))
        .pipe(gulp.dest(host.build + 'static'))
});

// 图片资源处理
gulp.task('img', () => {
    return gulp.src(host.path + 'img/**/*')
        .pipe(plumber())
        .pipe(changed(host.build))
        .pipe(gulp.dest(host.build + 'img'))
});

// json处理
gulp.task('json', () => {
    return gulp.src(host.path + '**/*.json')
        .pipe(changed(host.build))
        .pipe(debug({title: '编译:'}))
        .pipe(gulp.dest(host.build))
});

// 其他文件
gulp.task('other', () => {
    return gulp.src([host.path + '*.html', host.path + '*.js'])
        .pipe(plumber())
        .pipe(changed(host.build))
        .pipe(debug({title: '编译:'}))
        .pipe(gulp.dest(host.build))
});

// 删除文件
gulp.task('clean', () => {
    del(host.build + '/css');
    del(host.build + '/js');
    del(host.build + '/pages');
    del(host.build + '/static');
    del(host.build + '/img');
    del(host.build + '/index.html');
    del(host.build + '/login.html');
    del(host.build + '/config.js');
    del(host.build + '/*.json');
});

// 构建
gulp.task('build', (cb) => runSequence(
    ['html'], ['css'], ['pageJs'], ['static'], ['img'],['json'],['other']
)(cb));

gulp.task('default', ['serve']);

/* 命令 */
gulp.task('h', () => {
    log(chalk.yellow(''));
    log(chalk.yellow('     开发环境:           gulp  或  gulp --env 0'));
    log(chalk.yellow('     删除文件:           gulp clean'));
    log(chalk.yellow('     检查js代码:         gulp lint'));
    log(chalk.yellow('     修复可修复js代码:   gulp lint-fix'));
    log(chalk.yellow(''));
});

5.开发部署流程

配置好package.json和gulpfile.js文件后。执行

npm install 
注意事项

如果 npm install 时速度过慢,可以用cnpm,(cnpm需要安装,自行Google)。

开发:

所有的修改都是在app文件夹内,build后生成编译后的文件。

gulp // gulp default
部署:
gulp clean

gulp build

此示例为日常使用过程总结,部分代码有待优化。

相关文章

  • gulp资源整理

    Gulp官网 Gulp中文网 Gulp插件网 博客: 前端构建工具gulpjs的使用介绍及技巧 - 无双 gulp...

  • 『前端工程化』gulp(gulp3 && gul

    Gulp 什么是Gulp Gulp是基于Node.js的构建工具,我们使用它来集成前端开发环境,来构建自动化工作流...

  • 配置Gulp

    使用工具 Gulp说明 Gulp是前端开发过程中对代码进行构建的工具,是自动化项目的构建利器,基于node.js,...

  • 相关文章记录

    1.gulp构建工具相关信息 前端自动化构建工具gulp记录Gulp.js-livereload 不用F5了,实时...

  • 用自动化构建工具Gulp增强你的工作流程

    问:为什么要用在项目中使用前端自动化构建工具,gulp或其他等等。 答:先假设你没有使用这等前端自动化构建工具,你...

  • Glup

    Gulp 前端构建工具,类似webpack。 方便使用 构建快速 插件系统 易于学习 扩展插件可以在npmjs上搜...

  • gulp入门教程

    gulp是前端的自动化构建工具,gulp的出现是希望能取代grunt,成为最流行的前端自动化构建工具,它与grun...

  • gulp的基本使用

    gulp是什么 gulp是一个前端构建工具,通过脚本实现文件图片的压缩,gulp功能的实现依赖于插件,所以想使用什...

  • [译]Webpack前端构建集成方案

    构建工具逐渐成为前端工程必备的工具,Grunt、Gulp、Fis、Webpack等等,译者有幸使用过Fis、Gul...

  • 【前端工具】gulp构建工具的基本使用

    gulp是什么? gulp是前端开发中经常使用的自动化构建工具。自动化构建又是什么? 简单来说,一个完整的项目需要...

网友评论

    本文标题:前端构建工具 Gulp 的使用总结

    本文链接:https://www.haomeiwen.com/subject/yssijftx.html