gulp.js代码打包教程

1、全局安装gulp

cnpm install -g gulp

2、安装所需依赖包

cnpm install --save-dev [package]

gulp-babel //ES5转ES6
gulp-cheerio //html路径替换
gulp-concat //文件合并
gulp-cssnano //css压缩
gulp-htmlmin //html压缩
gulp-uglify //js压缩、混淆

3、在项目根目录新建文件gulpfile.js

'use strict';

var gulp = require('gulp');
var concat = require('gulp-concat');

//压缩css
var cssnano = require('gulp-cssnano');
gulp.task('style', function () {
gulp.src(['./css/**/*'])
.pipe(cssnano())
.pipe(gulp.dest('dist/css'));
});

//转ES5、压缩、混淆js
var babel = require('gulp-babel');
var uglify = require('gulp-uglify');
gulp.task('script', function () {
gulp.src(['./js/**/*'])
.pipe(babel({
presets: ['es2015']
}))
.pipe(concat('all.js'))
.pipe(uglify({
mangle: true,//类型:Boolean 默认:true 是否修改变量名
compress: true//类型:Boolean 默认:true 是否完全压缩
}))
.pipe(gulp.dest('dist/js'));
});


//压缩html
var htmlmin = require('gulp-htmlmin');
var cheerio = require('gulp-cheerio');
gulp.task('html', function () {
gulp.src('./*.html')
.pipe(cheerio(function ($) {
$('body script').remove();
$('body').append('<script src="js/all.js"></script>');
}))
.pipe(htmlmin({
collapseWhitespace: true,
removeComments: true
}))
.pipe(gulp.dest('dist'));
});

//复制static文件
gulp.task('static', function () {
gulp.src(['./static/**/*'])
.pipe(gulp.dest('dist/static'));
});

//执行打包
gulp.task('dist', ['style', 'script', 'html', 'static']);

//监听代码变化
gulp.task('watch', function () {
gulp.watch(['./css/*.css'], ['style']);
gulp.watch(['./js/*.js'], ['script']);
gulp.watch('./*.html', ['html']);
gulp.watch(['./static/**/*'], ['static']);
});

4、执行打包命令

gulp dist

5、监听文件变化,动态打包

gulp watch

 

 
posted @ 2018-11-12 09:40  付刚的博客  阅读(2391)  评论(0编辑  收藏  举报