2

我是 JavaScript 开发领域的新手,目前正在获得一个体面的工作流程。不过,我在理解 Gulp 的工作原理时遇到了一些麻烦。我已经使用 npm 安装了我的依赖项,并就我的能力编写了一个 gulpfile。

var gulp = require('gulp'), 
minifycss = require('gulp-minify-css'),
autoprefixer = require('gulp-autoprefixer'),
uglify = require('gulp-uglify'),
minifyhtml = require('gulp-minify-html'),
sass = require('sass'),
notify = require('gulp-notify');

gulp.task('js', function() {
    return gulp.src('js/**/*.js')
        .pipe(uglify({
            outSourceMap: true
        }))
        .pipe(gulp.dest('dist/assets/js'));
});

//This task should compile my scss-files into corresponding css-files in the css-folder. 
//If possible I would like to have it automatically detect which folder the file is in. 
//Ie: scss/user/main.scss should compile to css/user/main.css
gulp.task('sass', function() {
    return gulp.src('scss/*.scss')
        .pipe(sass())
        .pipe(gulp.dest('css'));
});

gulp.task('css', function() {
    return gulp.src('css/*.css')
        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios     6', 'android 4'))
        .pipe(minifycss())
        .pipe(gulp.dest('dist/assets/css'));
});

//This task should check all html-files in directory, and then minify them into     corresponding folders in dist/assets/html. 
//Ie: html/user/index.html should be minified into dist/assets/html/user/index.html.
gulp.task('html', function() {
    return gulp.src('html/*/*.html')
        .pipe(minifyhtml())
        .pipe(gulp.dest('dist/assets/html'));
});

//I know run() is depreceated. What to do? How should these be written?
gulp.task('default', function() {
    gulp.watch('scss/*.scss', function() {
        gulp.run('sass')
    });
    gulp.watch(['html/user/*.html', 'html/support/*.html'], function() {
        gulp.run('html');
    });
    gulp.watch('js/**/*.js', function() {
        gulp.run('js');
    });
    gulp.watch('css/*.css', function() {
        gulp.run('css');
    });
});

虽然它并没有真正像我想要的那样工作,并且在不知道要搜索什么的情况下进行谷歌搜索真的很难。我已经阅读了几个博客,但不幸的是无法掌握如何去做。我知道我不应该使用 run(),但是我应该如何编写代码呢?

如果有人可以用简单的英语解释依赖关系实际上是什么,我将不胜感激。在海上这个也是。

感谢您抽出宝贵的时间。

安东

4

1 回答 1

3

您可以使用内置的 gulp.watch 方法。gulp 的好处之一是您可以将常见任务声明为函数,然后重用它们。

下面是一个语法示例:

var paths = {
  scripts: './lib/**/*.js',
  tests: './test/**/*.js'
};

function lint(src){
  return gulp.src(src)
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter(stylish));
}

gulp.task('lint', function () { 
  lint([paths.scripts, paths.tests]);
});

gulp.task('test', function() { 
  // put your test pipeline here
});

gulp.task('watch', function () {

  // watch and lint any files that are added or changed
  gulp.watch([paths.scripts, paths.tests, paths.demo], function(event){
    if(event.type !== 'deleted') { 
      lint([event.path]); 
    }
  });

  // run all the tests when something changes
  gulp.watch([paths.scripts, paths.tests], ['test']); 

});
于 2014-02-18T21:23:54.827 回答