【问题标题】:How can I correctly read in multiple files inside a Gulp task?如何正确读取 Gulp 任务中的多个文件?
【发布时间】:2014-02-25 12:53:10
【问题描述】:

我有一个 Gulp 任务,它呈现一个包含 Lodash 模板的文件并将其放入我的构建目录中。我使用gulp-template 进行渲染。

为了正确渲染,我的模板需要从我的构建目录中传递一个文件列表。我使用glob 获取此列表。由于 glob API 是异步的,我不得不像这样编写我的任务:

gulp.task('render', function() {
    glob('src/**/*.js', function (err, appJsFiles) {

        // Get rid of the first path component.
        appJsFiles = _.map(appJsFiles, function(f) {
            return f.slice(6);
        });

        // Render the file.
        gulp.src('src/template.html')
            .pipe(template({
                scripts: appJsFiles,
                styles: ['style1.css', 'style2.css', 'style3.css']
            }))
            .pipe(gulp.dest(config.build_dir));
    });
});

这对我来说似乎很不雅。有没有更好的方法来编写这个任务?

【问题讨论】:

    标签: javascript gulp build-system


    【解决方案1】:

    解决您的特定问题的最简单方法是使用您链接到的文档中的synchronous mode for glob。然后返回gulp.src的结果。

    gulp.task('render', function() {
        var appJsFiles = _.map(glob.sync('src/**/*.js'), function(f) {
            return f.slice(6);
        });
        // Render the file.
        return gulp.src('src/template.html')
            .pipe(template({
                scripts: appJsFiles,
                styles: ['style1.css', 'style2.css', 'style3.css']
            }))
            .pipe(gulp.dest(config.build_dir));
    });
    

    【讨论】:

    • 我不知道 glob 有同步模式。这应该教我 RTFM:/
    【解决方案2】:

    如果您希望任务异步运行,请接收回调。

    gulp.task('render', function(cb) {
        glob('src/**/*.js', function (err, appJsFiles) {
            if (err) {
                return cb(err);
            }
    
            // Get rid of the first path component.
            appJsFiles = _.map(appJsFiles, function(f) {
                return f.slice(6);
            });
    
            // Render the file.
            gulp.src('src/template.html')
                .pipe(template({
                    scripts: appJsFiles,
                    styles: ['style1.css', 'style2.css', 'style3.css']
                }))
                .pipe(gulp.dest(config.build_dir))
                .on('end', cb);
       });
    });
    

    【讨论】:

    • 这个 cb() 永远不会退出 gulp
    • 现在试试,错过了 gulp.src 流。
    • 我不想做gulp.src。我需要我自己的带有元数据的文件对象列表。不可能吗?
    • 我不明白这个问题。您要解决的问题是什么?
    • 出于某种原因。某些 gulp 任务不会退出。他们只是在完成后挂起。
    猜你喜欢
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 2017-05-31
    • 1970-01-01
    相关资源
    最近更新 更多