Gulp 即时编译 SLIM/SASS/CoffeeScript

Gulp compiling SLIM/SASS/CoffeeScript on fly

有以下 Gulp 文件和任务:

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

// plugins
var connect = require('gulp-connect');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var minifyCSS = require('gulp-minify-css');
var clean = require('gulp-clean');
var slim = require('gulp-slim');
var coffee = require('gulp-coffee');
var sass = require('gulp-sass');

// tasks
gulp.task('lint', function() {
  gulp.src(['./app/**/*.js', '!./app/bower_components/**'])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'));
});

gulp.task('clean', function() {
    gulp.src('./dist/*')
      .pipe(clean({force: true}));
});

gulp.task('minify-css', function() {
  var opts = {comments:true,spare:true};
  gulp.src(['./app/**/*.scss', '!./app/bower_components/**'])
    .pipe(sass())
    .pipe(minifyCSS(opts))
    .pipe(gulp.dest('./dist/'))
});

gulp.task('minify-js', function() {
  gulp.src(['./app/**/*.coffee', '!./app/bower_components/**'])
    .pipe(coffee({bare: true}))
    .pipe(uglify({
      // inSourceMap:
      // outSourceMap: "app.js.map"
    }))
    .pipe(gulp.dest('./dist/'))
});

gulp.task('copy-bower-components', function () {
  gulp.src('./app/bower_components/**')
    .pipe(gulp.dest('dist/bower_components'));
});

gulp.task('copy-html-files', function () {
  gulp.src('./app/**/*.slim')
    .pipe(slim({ pretty: true }))
    .pipe(gulp.dest('dist/'));
});

gulp.task('connect', function () {
  connect.server({
    root: 'app/',
    port: 8888
  });
});

gulp.task('connectDist', function () {
  connect.server({
    root: 'dist/',
    port: 9999
  });
});


// default task
gulp.task('default',
  ['lint', 'connect']
);
// build task
gulp.task('build',
  ['lint', 'minify-css', 'minify-js', 'copy-html-files', 'copy-bower-components', 'connectDist']
);

我想在我的前端工作中使用SLIM/SASS/CoffeeScript。但我必须在每次更改后执行 'gulp clean build',以便将 SLIM 转换为 HTML,将 SASS 转换为 CSS,将 Coffee 转换为 JS。我想做任何更改,只需在浏览器中刷新页面即可。我该怎么做?提前致谢!

您需要在您的文件上放置观察者:

gulp.task('watch', ['build','connectDist'], function() {
    gulp.watch(['./app/**/*.coffee', '!./app/bower_components/**'], ['minify-js']);
    gulp.watch(['./app/**/*.scss', '!./app/bower_components/**'], ['minify-css']);
    gulp.watch('./app/**/*.slim', ['copy-html-files']);
})

如果您启动 gulp watch,首先会执行 buildconnectDist 任务,准备构建目录。然后三个观察者查看您的主要输入文件,并在发生变化时调用相关任务。

请注意,我调用了 connectDist 任务而不是 connect 任务,主要是因为所有浏览器可读文件都存储在 dist.