Browserify 大量使用文件系统,因为它实现了自己的模块解析,该解析使用与 Node 相同的算法require
。要让 Browserify 使用内存中的源文件进行捆绑,一种解决方案是对文件系统进行猴子修补 - 类似于mock-fs https://github.com/tschaub/mock-fs对测试有用的模块。
但是,您实际上只想对源文件执行此操作。 Browserify 对捆绑包中包含的其他文件使用其模块解析,并且必须将这些文件添加到内存文件系统中会很乏味。修补的文件系统函数应该检查涉及内存中源文件的调用,相应地处理它们并将其他调用转发到原始实现。 (mock-fs
做类似的事情,它检测发生在require
并将这些调用转发给原始实现。)
'use strict';
const fs = require('fs');
const path = require('path');
const toStream = require('string-to-stream');
// Create an object hash that contains the source file contents as strings,
// keyed using the resolved file names. The patched fs methods will look in
// this map for source files before falling back to the original
// implementations.
const files = {};
files[path.resolve('one.js')] =
'console.log("Hello from one.js");' +
'var two = require("./two");' +
'exports.one = 1;';
files[path.resolve('two.js')] =
'console.log("Hello from two.js");' +
'exports.two = 2;';
// The three fs methods that need to be patched take a file name as the
// first parameter - so the patch mechanism is the same for all three.
function patch(method, replacement) {
var original = fs[method];
fs[method] = function (...args) {
var name = path.resolve(args[0]);
if (files[name]) {
args[0] = name;
return replacement.apply(null, args);
} else {
return original.apply(fs, args);
}
};
}
patch('createReadStream', function (name) {
return toStream(files[name]);
});
patch('lstat', function (...args) {
args[args.length - 1](null, {
isDirectory: function () { return false; },
isFile: function () { return true; },
isSymbolicLink: function () { return false; }
});
});
patch('stat', function (...args) {
args[args.length - 1](null, {
isDirectory: function () { return false; },
isFile: function () { return true; }
});
});
// With the fs module patched, browserify can be required and the bundle
// can be built.
const browserify = require('browserify');
browserify()
.require(path.resolve('one.js'), { entry: true, expose: 'one' })
.require(path.resolve('two.js'), { expose: 'two' })
.bundle()
.pipe(process.stdout);
require
and expose
在你的问题中,你提到expose
. The one.js
and two.js
模块使用捆绑require
,因此可以使用在浏览器中指定的名称来要求它们expose
选项。如果这不是你想要的,你可以使用add
相反,它们将是捆绑包内部的模块。
<!doctype html>
<html>
<head>
<title>so-39397429</title>
</head>
<body>
<script src="./bundle.js"></script>
<script>
// At this point, the bundle will have loaded and the entry
// point(s) will have been executed. Exposed modules can be
// required in scripts, like this:
console.log(require('one'));
console.log(require('two'));
</script>
</body>
</html>
我花了一些时间研究 Browserifyrequire
and expose
调查时的选项这个问题 https://stackoverflow.com/q/38891391/6680611。这些选项有助于从捆绑包外部请求模块,但我完全不确定它们对捆绑包内模块之间的需求有任何影响(这就是您所需要的)。另外,他们的实现有点令人困惑 - 特别是这部分 https://github.com/substack/node-browserify/blob/13.1.0/index.js#L118-L128其中公开的名称有时会在前面加上斜杠。
乙烯基流
在你的问题中,你使用了vinyl
。但是,我无法使用vinyl
对于读取流。虽然它确实实现了pipe
,它不是一个事件发射器,并且似乎没有实现on
- 基于 pre-Streams 2 API - 这是 Browserify 对createReadStream
result.