Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 知乎專欄 | Search | About

4.5. JS Minification

		
npm install --save-dev gulp-uglify
		
		

gulpfile.js:

		
// including plugins
var gulp = require('gulp');
var uglify = require("gulp-uglify");
 
// task
gulp.task('minify-js', function () {
    gulp.src('./JavaScript/*.js') // path to your files
    .pipe(uglify())
    .pipe(gulp.dest('path/to/destination'));
});
		
		

Run:

		
gulp minify-js
		
		

4.5.1. JS 校驗

			
var gulp = require('gulp');
var header = require('gulp-header');  //給文本檔案頭部追加內容
var footer = require('gulp-footer');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint'); //js代碼校驗
var cached = require('gulp-cached');
var remember = require('gulp-remember'); //gulp-remember is a gulp plugin that remembers files that have passed through it. gulp-remember adds all the files it has ever seen back into the stream.

gulp.task('scripts', function() {
  return gulp.src('src/**/*.js')
      .pipe(cached('scripts'))        // 只傳遞更改過的檔案 
      .pipe(jshint())                 // 對這些更改過的檔案做一些特殊的處理...
      .pipe(header('(function () {')) // 比如 jshinting ^^^
      .pipe(footer('})();'))          // 增加一些類似模組封裝的東西
      .pipe(remember('scripts'))      // 把所有的檔案放回 stream
      .pipe(concat('main.js'))         // 合併檔案的操作
      .pipe(gulp.dest('public/'));
});