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

第 4 章 gulpjs

目錄

4.1. Tasks automation
4.1.1. gulp-changed
4.1.2. 顯示處理進度
4.1.3. notify
4.1.4. del
4.1.5. start
4.2. watch
4.3. HTML Minification
4.4. CSS Minification
4.4.1. gulp-minify-css
4.4.2. gulp-clean-css
4.4.3. gulp-make-css-url-version
4.4.4. CSS 冗餘分析
4.5. JS Minification
4.5.1. JS 校驗
4.6. CSS Sprite
4.7. Compress Images
4.8. WEBP格式圖片
4.9. Sass Compilation
4.10. Less Compilation
4.11. 重命名檔案名
4.12. 合併檔案
4.13. 檔案頭
4.14. yargs 命令行參數傳遞
4.14.1. gulp-util
4.14.2. minimist
4.15. gulp-sourcemaps
4.16. gulp-zip
4.17. 清理JS中的console.log()調試語句
4.18. copy-dir
4.19. gulp-copy
4.20.
4.21. Example
4.21.1. HTML,JS,CSS
4.21.2. 命令行傳遞參數

安裝

npm install gulp-cli
npm install gulp -D
	

創建 gulpfile.js 檔案

	
var gulp = require('gulp');
var pug = require('gulp-pug');
var less = require('gulp-less');
var minifyCSS = require('gulp-csso');

gulp.task('html', function(){
  return gulp.src('client/templates/*.pug')
    .pipe(pug())
    .pipe(gulp.dest('build/html'))
});

gulp.task('css', function(){
  return gulp.src('client/templates/*.less')
    .pipe(less())
    .pipe(minifyCSS())
    .pipe(gulp.dest('build/css'))
});

gulp.task('default', [ 'html', 'css' ]);
	
	

排除目錄

	
gulp.src(['js/**/*.js', '!js/**/*.min.js'])
	
	

	
	

4.1. Tasks automation

4.1.1. gulp-changed

			
// npm install --save-dev gulp gulp-changed gulp-jscs gulp-uglify

var gulp = require('gulp');
var changed = require('gulp-changed');
var jscs = require('gulp-jscs');
var uglify = require('gulp-uglify');

var SRC = 'src/**/*.js';
var DEST = 'dist';

gulp.task('default', function() {
    return gulp.src(SRC)
        .pipe(changed(DEST)) // changed 任務需要提前知道目標目錄位置才能找出哪些檔案是被修改過的,只有被更改過的檔案才會通過這裡
        .pipe(jscs())
        .pipe(uglify())
        .pipe(gulp.dest(DEST));
});	
			
			

4.1.2. 顯示處理進度

顯示處理中的檔案

			
gulp.task('minify-css', function () {

        gulp.src([src + '/**/css/**/*.css', "!"+src + '/**/css/**/*.min.css'])
        .on('data', function(file) {
                console.log('%s Read %d bytes of data', file.path, file.contents.length);
        })
        .pipe(concat("finally.css"))
        .pipe(rename({ suffix: '.min' }))
        .pipe(minifycss())
        .pipe(gulp.dest( dist ));

});	
			
			

4.1.3. notify

			
npm install --save-dev gulp-notify
			
			
			
var notify = require('gulp-notify');
			
			
			
.pipe(notify({ message: 'Styles task complete' }));
			
			

4.1.4. del

			
var gulp = require('gulp');
var del = require('del');

gulp.task('clean:mobile', function (cb) {
  del([
    'dist/**/css/*.min.css',
    'dist/mobile/**/*',
    '!dist/mobile/deploy.json'
  ], cb);
});

gulp.task('default', ['clean:mobile']);			

// Clean
gulp.task('clean', function() {
	return del(['dist/styles', 'dist/scripts', 'dist/images']);
});
			
			

4.1.5. start

			
// Default task
gulp.task('default', ['clean'], function() {
	gulp.start('styles', 'scripts', 'images');
});