$ npm install --global yo generator-webapp
$ mkdir my-webapp $ cd my-webapp $ yo webapp
$ gulp serve
這將啓動本地Web服務器,在默認瀏覽器中打開http://localhost:9000
並查看文件以進行更改,經過LiveReload自動從新加載瀏覽器。javascript
$ gulp serve:test
$ gulp
$ gulp serve:dist
$ gulp --tasks
使用.tmp目錄來編譯像SCSS文件這樣的資源。它優先於app,因此若是你有一個app/main.scss 模板編譯.tmp/main.css,http://localhost:9000
會指向.tmp/main.css,這是咱們想要的。css
上圖可見其引入的樣式文件是.tmp/main.css,控制檯顯示的是source map映射文件(main.scss)html
【gulpfile.js配置 --- app->.tmp】java
//app目錄下的scss文件和js文件編譯到.tmp目錄下 gulp.task('styles', () => { return gulp.src('app/styles/*.scss') .pipe($.plumber()) .pipe($.if(dev, $.sourcemaps.init())) .pipe($.sass.sync({ outputStyle: 'expanded', precision: 10, includePaths: ['.'] }).on('error', $.sass.logError)) .pipe($.autoprefixer({browsers: ['> 1%', 'last 2 versions', 'Firefox ESR']})) .pipe($.if(dev, $.sourcemaps.write())) .pipe(gulp.dest('.tmp/styles')) .pipe(reload({stream: true})); }); gulp.task('scripts', () => { return gulp.src('app/scripts/**/*.js') .pipe($.plumber()) .pipe($.if(dev, $.sourcemaps.init())) .pipe($.babel()) .pipe($.if(dev, $.sourcemaps.write('.'))) .pipe(gulp.dest('.tmp/scripts')) .pipe(reload({stream: true})); }); //app下的html文件更新對js和css文件的引用路徑 gulp.task('html', ['styles', 'scripts'], () => { return gulp.src('app/*.html') .pipe($.useref({searchPath: ['.tmp', 'app', '.']})) .pipe($.if(/\.js$/, $.uglify({compress: {drop_console: true}}))) .pipe($.if(/\.css$/, $.cssnano({safe: true, autoprefixer: false}))) .pipe($.if(/\.html$/, $.htmlmin())) .pipe(gulp.dest('dist')); });
下圖顯示了在同域名下html引用.tmp目錄下的css和js文件,同時也保存了其對map文件的映射ios
var gulp = require('gulp'); var browserSync = require('browser-sync').create();// require 加載 browser-sync 模塊 var sass = require('gulp-sass'); var reload = browserSync.reload; // 靜態服務器 + 監聽 scss/html 文件 gulp.task('serve', ['sass'], function() { // .init 啓動服務器 browserSync.init({ server: "./app" }); gulp.watch("app/scss/*.scss", ['sass']); gulp.watch("app/*.html").on('change', reload); }); // scss編譯後的css將注入到瀏覽器裏實現更新 gulp.task('sass', function() { return gulp.src("app/scss/*.scss") .pipe(sass()) .pipe(gulp.dest("app/css")) .pipe(reload({stream: true})); }); gulp.task('default', ['serve']);
配置參數:git
.init( config, cb )github
// Serve files from the app directory server: "app" // Serve files from the current directory server: true // Serve files from the app directory with directory listing server: { baseDir: "app", directory: true } // Multiple base directories server: ["app", "dist"] // Serve files from the app directory, with a specific index filename server: { baseDir: "app", index: "index.htm" } // The static file server is based on expressjs/serve-static, // so we inherit all of their options, like trying a default extension // when one isn't specified // https://github.com/expressjs/serve-static server: { baseDir: "app", serveStaticOptions: { extensions: ["html"] } } // Since version 1.2.1 // The key is the url to match // The value is which folder to serve (relative to your current working directory) server: { baseDir: "app", routes: { "/bower_components": "bower_components" } }
【gulpfile.js配置 --- browserSync.init】web
gulp.task('serve', () => { runSequence(['clean', 'wiredep'], ['styles', 'scripts', 'fonts'], () => { browserSync.init({ notify: false, port: 9000, server: { baseDir: ['.tmp', 'app'], routes: { '/bower_components': 'bower_components' } } }); gulp.watch([ 'app/*.html', 'app/images/**/*', '.tmp/fonts/**/*' ]).on('change', reload); gulp.watch('app/styles/**/*.scss', ['styles']); gulp.watch('app/scripts/**/*.js', ['scripts']); gulp.watch('app/fonts/**/*', ['fonts']); gulp.watch('bower.json', ['wiredep', 'fonts']); }); });
Browsersync / 說明文檔express
將Bower依賴自動注入HTML文件中。使用--save安裝Bower軟件包會將軟件包做爲依賴項添加到項目的bower.json文件中。 該庫(wiredep)讀取該文件(.html),而後讀取bower.json文件的每一個依賴項。 基於二者間關聯,它決定了腳本在源代碼中的佔位符之間注入以前必須包含的順序。npm
<html> <head> <!-- bower:css --> <!-- endbower --> </head> <body> <!-- bower:js --> <!-- endbower --> </body> </html> var wiredep = require('wiredep').stream; gulp.task('bower', function () { gulp.src('./src/footer.html') .pipe(wiredep({ optional: 'configuration', goes: 'here' })) .pipe(gulp.dest('./dest')); });
經過讀取並分析bower.json文件裏override屬性裏main路徑下定義的插件及相關依賴,返回一個文件數組。
若是第一個參數是String,Array或RegExp的類型,它將被用做過濾器,不然將被用做選項。
讀取您的bower.json,遍歷您的依賴關係,並返回在bower.json的由main屬性的值組成的對象數組。
若是將一個overrides 屬性添加到您本身的bower.json中,則能夠複寫執行。
var mainBowerFiles = require('main-bower-files'); var files = mainBowerFiles([[filter, ]options][, callback]);
var gulp = require('gulp'); var mainBowerFiles = require('main-bower-files'); gulp.task('TASKNAME', function() { return gulp.src(mainBowerFiles()) .pipe(/* what you want to do with the files */) });
var gulp = require('gulp'); var mainBowerFiles = require('main-bower-files'); gulp.task('TASKNAME', function() { return gulp.src(mainBowerFiles(/* options */), { base: 'path/to/bower_components' }) .pipe(/* what you want to do with the files */) });
run-sequence 的做用就是控制多個任務進行順序執行或者並行執行
del 全局刪除文件/文件夾.
var gulp = require('gulp'); var runSequence = require('run-sequence'); var del = require('del'); // This will run in this order: // * build-clean // * build-scripts and build-styles in parallel // * build-html // * Finally call the callback function gulp.task('build', function(callback) { runSequence('build-clean', ['build-scripts', 'build-styles'], 'build-html', callback); }); gulp.task('build-clean', function() { // Return the Promise from del() return del(['tmp/*.js', '!tmp/unicorn.js']).then(paths => { console.log('Deleted files and folders:\n', paths.join('\n')); }); });
提供source map支持。若是調用 sourcemaps.write
不給任何參數,不會生成一個 .map 的文件,默認會將文件對照表信息所有寫入轉碼編譯後的文件末端。這樣很不友好。(通常這個對照表的信息量仍是很大的,這對生產線上瀏覽器請求加載文件無疑是無用額外的開銷,手動去除也是一件很低效費時的工做。)
咱們能夠給它加個參數。這樣指定輸出路徑以後,文件編譯轉碼完只會在最後一行只會寫入對 Source Map 的文件引用,而 Source Map 對照表自己(.map文件)會被輸出到指定的路徑下
//@ sourceMappingURL=_srcmap/BearD01001.js.map
var gulp = require('gulp'); var plugin1 = require('gulp-plugin1'); var plugin2 = require('gulp-plugin2'); var sourcemaps = require('gulp-sourcemaps'); gulp.task('javascript', function() { gulp.src('src/**/*.js') .pipe(sourcemaps.init()) .pipe(plugin1()) .pipe(plugin2()) .pipe(sourcemaps.write('../maps')) .pipe(gulp.dest('dist')); });
解析HTML文件中的構建塊,以替換對未優化的腳本或樣式表的引用。合併成一個文件,但不負責代碼壓縮
var gulp = require('gulp'), useref = require('gulp-useref'); gulp.task('default', function () { return gulp.src('app/*.html') .pipe(useref()) .pipe(gulp.dest('dist')); }); <!-- build:<type>(alternate search path) <path> <parameters> --> ... HTML Markup, list of script / link tags. <!-- endbuild -->
完整形式的示例以下所示:
<html> <head> <!-- build:css css/combined.css --> <link href="css/one.css" rel="stylesheet"> <link href="css/two.css" rel="stylesheet"> <!-- endbuild --> </head> <body> <!-- build:js scripts/combined.js --> <script type="text/javascript" src="scripts/one.js"></script> <script type="text/javascript" src="scripts/two.js"></script> <!-- endbuild --> </body> </html>
生成的HTML將是:
<html> <head> <link rel="stylesheet" href="css/combined.css"/> </head> <body> <script src="scripts/combined.js"></script> </body> </html>
var gulpif = require('gulp-if'); var uglify = require('gulp-uglify'); var beautify = require('gulp-beautify'); var condition = function (file) { // TODO: add business logic return true; } //If condition returns true, uglify else beautify, then send everything to the dist folder gulp.task('task', function() { gulp.src('./src/*.js') .pipe(gulpif(condition, uglify(), beautify())) .pipe(gulp.dest('./dist/')); }); //Only uglify the content if the condition is true, but send all the files to the dist folder gulp.task('task2', function() { gulp.src('./src/*.js') .pipe(gulpif(condition, uglify())) .pipe(gulp.dest('./dist/')); });
var gulp = require('gulp'); var gulpLoadPlugins = require('gulp-load-plugins'); var plugins = gulpLoadPlugins();
plugins.clone= require(‘gulp-clone’);
plugins.cleanCss= require(‘gulp-clean-css’);
var autoprefixer = require('gulp-autoprefixer'); gulp.src('./css/*.css') .pipe(autoprefixer()) // 直接添加前綴 .pipe(gulp.dest('dist')) gulp.src('./css/*.css') .pipe(autoprefixer({ browsers: ['last 2 versions'], // 瀏覽器版本 cascade:true // 美化屬性,默認true add: true // 是否添加前綴,默認true remove: true // 刪除過期前綴,默認true flexbox: true // 爲flexbox屬性添加前綴,默認true })) .pipe(gulp.dest('./dist'))
browsers參數詳解 (傳送門):
各瀏覽器的標識:
gulp-cached 能夠將第一次傳遞給它的文件內容保留在內存中,若是以後再次執行 task,它會將傳遞給它的文件和內存中的文件進行比對,若是內容相同,就再也不將該文件繼續向後傳遞,從而作到了只對修改過的文件進行增量編譯。
var cache = require('gulp-cached'); gulp.task('lint', function(){ return gulp.src('files/*.js') .pipe(cache('linting')) .pipe(jshint()) .pipe(jshint.reporter()) }); gulp.task('watch', function(){ gulp.watch('files/*.js', ['lint']); }); gulp.task('default', ['watch','lint']);
gulp 中的增量編譯
gulp-changed的使用:只編譯改動過的文件
使用全局正則匹配模式對原始文件的子集進行過濾。 當完成操做並想要全部的原始文件時,只需使用restore恢復流。
var filter = require('gulp-filter'); const f = filter(['**', '!*/index.js']); gulp.src('js/**/*.js') .pipe(f) // 過濾掉index.js這個文件 .pipe(gulp.dest('dist')); const f1 = filter(['**', '!*/index.js'], {restore: true}); gulp.src('js/**/*.js') .pipe(f1) // 過濾掉index.js這個文件 .pipe(uglify()) // 對其餘文件進行壓縮 .pipe(f1.restore) // 返回到未過濾執行的全部文件 .pipe(gulp.dest('dist')); // 再對全部文件操做,包括index.js
var gulp = require('gulp'), htmlmin = require('gulp-htmlmin'); gulp.task('testHtmlmin', function () { var options = { removeComments: true,//清除HTML註釋 collapseWhitespace: true,//壓縮HTML collapseBooleanAttributes: true,//省略布爾屬性的值 <input checked="true"/> ==> <input /> removeEmptyAttributes: true,//刪除全部空格做屬性值 <input id="" /> ==> <input /> removeScriptTypeAttributes: true,//刪除<script>的type="text/javascript" removeStyleLinkTypeAttributes: true,//刪除<style>和<link>的type="text/css" minifyJS: true,//壓縮頁面JS minifyCSS: true//壓縮頁面CSS }; gulp.src('src/html/*.html') .pipe(htmlmin(options)) .pipe(gulp.dest('dist/html')); });
var gulp = require('gulp'), imagemin = require('gulp-imagemin'); gulp.task('testImagemin', function () { gulp.src('src/img/*.{png,jpg,gif,ico}') .pipe(imagemin()) .pipe(gulp.dest('dist/img')); });
這個補丁插件用來解決gulp管道流的問題。簡而言之,它將替換管道流的默認方式,並刪除錯誤事件上的標準錯誤處理程序(默認狀況下會錯誤地處理錯誤流)
var plumber = require('gulp-plumber'); var coffee = require('gulp-coffee'); gulp.src('./src/*.ext') .pipe(plumber()) .pipe(coffee()) .pipe(gulp.dest('./dist'));
Minify JavaScript with UglifyJS3.
var gulp = require('gulp'), uglify = require('gulp-uglify'); gulp.task('jsmin', function () { gulp.src('src/js/index.js') .pipe(uglify()) .pipe(gulp.dest('dist/js')); });