Gulp Bundle + Browserify多个文件

Gulp Bundle + Browserify on multiple files

本文关键字:文件 Browserify Bundle Gulp      更新时间:2023-09-26

所以我有一个简单的gulp任务函数,目前转换我的主。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"))
});

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

  • 主要。

  • otherPage。

  • otherPage2。

All in one gulp任务。

我在网上搜索过,但似乎找不到任何相关的东西,任何帮助或建议都很感激,提前谢谢你。

如果你想为每个文件创建一个bundle,你需要在各自的文件上循环,为每个文件创建一个流,然后合并流(使用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"))
  }));
});

上面的操作要求您手动维护一个文件列表作为数组。也可以编写一个任务,将app目录中的所有.jsx文件捆绑在一起,而不必维护文件的显式数组。您只需要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"))
  }));
});