Gulp Bundle + Browserify在多个文件上

dan*_*mcr 5 javascript jsx browserify reactjs gulp

所以我有一个简单的gulp任务函数,它目前将我的main.jsx转换为main.js文件:

gulp.task("bundle", function () {
    return browserify({
        entries: "./app/main.jsx",
        debug: true
    }).transform(reactify)
        .bundle()
        .pipe(source("main.js"))
        .pipe(gulp.dest("app/dist"))
});
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以在这个gulp.task中放置多个bundle? 我理想的结果是能够做到:

  • main.jsx到main.js

  • otherPage.jsx到otherPage.js

  • otherPage2.jsx到otherPage2.js

一气呵成的任务.

我搜索了onliine但似乎找不到任何相关的内容,感谢任何帮助或建议,谢谢你提前.

Sve*_*ung 8

如果要为每个文件创建一个包,需要在各个文件上循环,为每个文件创建一个流,然后合并这些流(使用merge-stream):

var merge = require('merge-stream');

gulp.task("bundle", function () {
  var files = [ "main", "otherPage", "otherPage2" ];
  return merge(files.map(function(file) {
    return browserify({
        entries: "./app/" + file + ".jsx",
        debug: true
    }).transform(reactify)
        .bundle()
        .pipe(source(file + ".js"))
        .pipe(gulp.dest("app/dist"))
  }));
});
Run Code Online (Sandbox Code Playgroud)

以上要求您手动将文件列表维护为数组.还可以编写一个捆绑目录中所有.jsx文件的任务,app而无需维护文件的显式数组.您只需要glob包来确定您的文件数组:

var merge = require('merge-stream');
var glob = require('glob');
var path = require('path');

gulp.task("bundle", function () {
  var files = glob.sync('./app/*.jsx');
  return merge(files.map(function(file) {
    return browserify({
        entries: file,
        debug: true
    }).transform(reactify)
        .bundle()
        .pipe(source(path.basename(file, '.jsx') + ".js"))
        .pipe(gulp.dest("app/dist"))
  }));
});
Run Code Online (Sandbox Code Playgroud)