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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM