gulp-inject使用时遇到的坑

'use strict';

var gulp = require('gulp');
var less = require('gulp-less');
var minifycss = require('gulp-minify-css');
var rename = require("gulp-rename");
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var gutil = require('gulp-util');

// load plugins
var $ = require('gulp-load-plugins')();
var hash = require('gulp-hash');
var inject = require('gulp-inject');
// handle *.less
gulp.task('styles', function() {
  return gulp.src(['less/xxx.less'])
  .pipe(less())
  .pipe($.autoprefixer('last 1 version'))
  .pipe(minifycss())
  .pipe(gulp.dest('css'))
  .pipe(reload({stream: true}))
  .pipe($.size())
});
// handle *.js
gulp.task('scripts', function() {
  return gulp.src('js/xxx.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter(require('jshint-stylish')))
    .pipe(gulp.dest('js'))
    .pipe($.size());
});
// handle html, depend on styles and scripts
gulp.task('html', ['scripts', 'styles'], function() {
  var jsFilter = $.filter('**/*.js', {restore: true}),
    cssFilter = $.filter('**/*.css', {restore: true});
  return gulp.src('index.html')  // 1. 这里如果写成['**/*.html'],htmls任务则不需要
    .pipe($.useref())
    .pipe(jsFilter)
    .pipe(hash({hashLength: 12}))
    .pipe($.uglify())
    .pipe(jsFilter.restore)
    .pipe(cssFilter)
    .pipe(hash({hashLength: 12}))
    .pipe($.csso())
    .pipe(cssFilter.restore)
    .pipe($.useref())
    .pipe(gulp.dest('dist'))
    .pipe($.size());
});
// handle copy images
gulp.task('images', function() {
  return gulp.src('img/xxx/**/*')
    .pipe(gulp.dest('dist/img/xxx'))
    .pipe(reload({stream: true, once: true}))
    .pipe($.size());
});
// handle copy htmls
gulp.task('htmls', function() {
  return gulp.src(['*.html', '!index.html'])   // 2. 或者如1位置,这里进行拷贝时,则需要将index.html屏蔽
    .pipe(gulp.dest('dist'))
    .pipe(reload({stream: true, once: true}))
    .pipe($.size());
});
// clean
gulp.task('clean', function() {
  return gulp.src(['dist'], {read: false}).pipe($.clean());
});
// inject
gulp.task('inject', ['html'], function() {
  var target = gulp.src('dist/**/*.html'),
    sources = gulp.src([ 'dist/js/vendor-*.js', 'dist/js/xxx-*.js','dist/css/xxx-*.css'], {read: false});

  return target.pipe(inject(sources, {relative: true}))
    .pipe(gulp.dest('dist'));
});
// build
gulp.task('build', ['clean'], function() {
  gulp.start(['inject', 'images', 'htmls']);
});
// dev
gulp.task('dev', ['watch']);
// default
gulp.task('default', ['clean'], function() {
  gulp.start('build');
});

gulp.task('serve', ['styles'], function () {
    browserSync.init({
        port: 3200,
        server: {
            baseDir: ''
        }
    });
});

gulp.task('watch', ['serve'], function () {

    // watch for changes
    gulp.watch(['*.html'], reload);

    gulp.watch('less/**/*.less', ['styles']);
    gulp.watch('js/**/*.js', ['scripts']);
    gulp.watch('img/**/*', ['images']);
});

你可能感兴趣的:(gulp-inject使用时遇到的坑)