简单gulp.js

引入相对应的文件

let gulp = require("gulp");
let inject = require("gulp-inject");
let cleanCss = require("gulp-clean-css");
let uglify = require("gulp-uglify");
let pump = require("pump");
let cache = require("gulp-cache");
let rename = require("gulp-rename");
let imagemin = require("gulp-imagemin"); //图片压缩
let less = require("gulp-less"); //less编译成css
let clean = require("gulp-clean"); // gulp之前将之前的dist文件清除
let runSequence = require("run-sequence");
let series = require('stream-series');
gulp.task("default", ["clean:dist"], function(){
  runSequence("inject");
  // gulp.watch("src/less/*.less", ["less"]);
});

清除文件,一般执行在default之前

//clean:dist
gulp.task("clean:dist", function() {
  return gulp.src(["dist/images", "dist/js", "dist/css"], {
    read: false
  })
  .pipe(clean());
});

将less解压成css

// less 文件
gulp.task("less", function () {
  return gulp.src("src/less/*.less")
    .pipe(less())
    .pipe(gulp.dest("src/css"));
});

压缩js

// 压缩 js
gulp.task("js", function(cb){
  pump([
    gulp.src("src/js/*.js"),
    uglify(),
  gulp.dest("dist/js")
  ], cb);
});

压缩图片

// 图片
gulp.task("images", function() {
  return gulp.src("src/images/*")
    .pipe(cache(imagemin({
      optimizationLevel: ,
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest("dist/images"));
});

压缩css

// 压缩css
gulp.task("css", ["less"], function(){
  return gulp.src("src/css/*.css")
    .pipe(cleanCss({debug: true}))
    .pipe(rename({suffix: ".min"}))
    .pipe(gulp.dest("dist/css"));
});

将css文件注入

gulp.task("inject", ["images", "css", "js"], function(){
  let sourcesIndex = gulp.src(['./dist/css/*.css', '!./dist/css/style.min.css'], {read: false});
  let sourcesCommon = gulp.src(['./dist/css/style.min.css'], {read: false});
  return gulp.src("./src/index.html")
    .pipe(inject(series(sourcesIndex, sourcesCommon), {
      relative: true,
      transform: function (filepath) {
        var filename=filepath.substring(filepath.lastIndexOf("/") + );
        return '<link rel="stylesheet" href="css/'+ filename +'"/>';
      }}))
  .pipe(gulp.dest("./dist"));
});
上一篇:如何选择PDA的操作系统? Android OR WINCE?


下一篇:湖大 11404 manacher