1. 程式人生 > >前端自動化構建之 gulp 合併 壓縮 加版本號

前端自動化構建之 gulp 合併 壓縮 加版本號

先安裝nodejs

cmd 控制檯

cd到網站目錄下

安裝gulp及一些用到的外掛

npm install -g gulp
npm install --save-dev gulp
npm install --save-dev gulp-watch
npm install --save-dev require-dir
npm install --save-dev gulp
npm install gulp-rev gulp-rev-collector --save-dev

還有其它這裡沒有一一列出

也可以用package.json檔案直接還原包:

{
  "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-asset-rev": "0.0.15",
    "gulp-concat": "^2.6.1",
    "gulp-csso": "^3.0.1",
    "gulp-filter": "^5.1.0",
    "gulp-imagemin": "^4.1.0",
    "gulp-less": "^3.4.0",
    "gulp-replace": "^0.6.1",
    "gulp-rev": "^8.1.1",
    "gulp-rev-replace": "^0.4.4",
    "gulp-uglify": "^3.0.0",
    "gulp-useref": "^3.1.4",
    "gulp-watch": "^5.0.0",
    "require-dir": "^0.3.2"
  },
  "name": "gulp",
  "version": "1.0.0",
  "description": "felix",
  "main": "gulpfile.js",
  "dependencies": {
    "gulp": "^3.9.1",
    "gulp-watch": "^5.0.0",
    "require-dir": "^0.3.2"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
gulpfile.js:
var gulp = require('gulp');
var rev = require('gulp-rev');/*給檔案用雜湊碼新增版本號*/
var revReplace = require('gulp-rev-replace');/*更新引用*/
var useref = require('gulp-useref');/*合併檔案*/
var filter = require('gulp-filter');/*過濾器:篩選,恢復*/
var uglify = require('gulp-uglify');/*壓縮js*/
var csso = require('gulp-csso');/*壓縮css*/
var concat = require('gulp-concat'); //引用 

var assetRev = require('gulp-asset-rev'); 
var replace = require('gulp-replace')
var imageMin = require('gulp-imagemin');

gulp.task('rev', ['revjs'], function () {
    gulp.src("*.html").pipe(replace(/\?v=\w*/g, ''))
        .pipe(assetRev())
        .pipe(gulp.dest(''));
});

gulp.task('revjs', function () {
    return    gulp.src(['js/*.js']).pipe(concat('main.min.js')).pipe(uglify({ mangle: { toplevel: true } })).pipe(gulp.dest('js/build/'));
});

vs2017的效果: