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

 

 

转载于:https://www.cnblogs.com/sharealex/articles/9944806.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值