加载文件后运行gulp任务

Running gulp task after loading file

本文关键字:gulp 任务 运行 文件 加载      更新时间:2023-09-26

我正在尝试复制,连接和缩小特定的javascript文件到一个dist bower_components目录使用manifest JSON文件,以保持事情更干净。

我想在一个单独的任务中运行concat和uglify,但是文件加载的延迟意味着任何依赖的任务在它完成之前运行。

// editorial tools gulp file
var gulp = require("gulp");
var path = require("path"),
argv = require("yargs").argv,
fs = require("fs"),
runSequence = require("run-sequence");
// load plugins
var $ = require("gulp-load-plugins")({ lazy: false });
gulp.task("other-task", ["read-manifest"], function () {
    // something else before read-manifest...
});
gulp.task("read-manifest", function () {
var cwd = process.cwd();
// vendor JS to compile (get manifest of files to bring in)
fs.readFile(cwd + "/src/bower_manifest.json", "utf-8", function (err, _data) {
    if (err) {
        console.log("Error: " + err);
        return;
    }
    // manifest string to JSON
    data = JSON.parse(_data);
    // copy bower files in manifest
    var fileList = data.fileUrls,
        loadOrder = data.loadOrder,
        filesToCopy = [];
    for ( var i = 0, len = loadOrder.length; i < len; i ++ ) {
        filesToCopy.push("./src/bower_components/" + fileList[loadOrder[i]]);
    }
    // add shared js
    filesToCopy.push("./src/javascripts/*.js");
    console.log(filesToCopy);
    // concat and uglify
    return gulp.src(filesToCopy)
        .pipe($.concat("shared.min.js"))
        // .pipe($.uglify())
        .pipe(gulp.dest("./dist/javascripts/"));
    $.util.log($.util.colors.green("JS combined and uglified"));
});
});
控制台:

[gulp] Starting 'read-manifest'...
[gulp] Finished 'read-manifest' after 476 μs
[gulp] Starting 'other-task'...
[ './src/bower_components/jquery/jquery.min.js',
  './src/bower_components/aight/aight.min.js',
  './src/bower_components/d3/d3.min.js',
  './src/bower_components/aight/aight.d3.min.js',
  './src/javascripts/*.js' ]
[gulp] Finished 'other-task' after 15 ms

据我所知,您遇到的主要问题是您试图将此任务用作另一个任务的依赖项,并且该任务在此任务完成之前开始。

为了支持异步任务,你需要返回一个promise一个stream或者调用一个done回调。现在要做的是返回一个流,但是在回调中。因此,任务函数将不会返回流(因为它是异步的)。更简单的方法是使用promise或callback..

使用回调的例子:

// note the "done" callback
gulp.task("read-manifest", function (done) {
    var cwd = process.cwd();
    // vendor JS to compile (get manifest of files to bring in)
    fs.readFile(cwd + "/src/bower_manifest.json", "utf-8", function (err, _data) {
         if (err) {
             console.log("Error: " + err);
             return;
         }
         // ... etc ...
        gulp.src(filesToCopy)
            .pipe($.concat("shared.min.js"))
            // .pipe($.uglify())
            .pipe(gulp.dest("./dist/javascripts/"))
            // when stream ends, call callback
            .on('end', done); 
    });
});

或者你可以使用这样的承诺:

var Q = require('q');
gulp.task("read-manifest", function () {
    var deferred = Q.defer();
    var cwd = process.cwd();
    // vendor JS to compile (get manifest of files to bring in)
    fs.readFile(cwd + "/src/bower_manifest.json", "utf-8", function (err, _data) {
         if (err) {
             console.log("Error: " + err);
             return;
         }
         // ... etc ...
        gulp.src(filesToCopy)
            .pipe($.concat("shared.min.js"))
            // .pipe($.uglify())
            .pipe(gulp.dest("./dist/javascripts/"))
            // when stream ends, call callback
            .on('end', function () {
                 deferred.resolve();
            }); 
    });
    return deferred.promise;
});

这有意义吗?这样,依赖项就知道任务何时完成。在文档

中阅读更多关于异步支持的信息
// gulpfile.js
var gulp = require('gulp');
var Promise = require('promise');
gulp.task('lazy-load-task', function(){
    var LazyLoad = require('your-lazy-load-js');
    return new Promise(function(resolve, reject){
        // define your lazy task depends on LazyLoad
        gulp.task('lazy-task', function(){
            // TODO: do your logic with LazyLoad here
            resolve(0);
            return Promise.resolve(0); // optional
        });
        // execute it
        gulp.start('lazy-task');
    });
});
gulp.task('default', ['lazy-load-task']);