我是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(),但是我应该如何编写代码?
如果有人能用简单的英语解释一下依赖是什么,我会非常感激。在这个海上也是如此。
感谢您抽出宝贵时间。
安东
答案 0 :(得分: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']);
});