Why can I not use a variable as parameter in the require() function of node.js (browserify)?

rum*_*ore 7 javascript node.js browserify reactjs

I tried something like:

var path = '../right/here';
var module = require(path);
Run Code Online (Sandbox Code Playgroud)

but it can't find the module anymore this way, while:

var module = require('../right/here');
Run Code Online (Sandbox Code Playgroud)

works like a charm. Would like to load modules with a generated list of strings, but I can't wrap my head around this problem atm. Any ideas?

Gau*_*ani 6

您可以使用模板动态获取文件。

var myModule = 'Module1';
var Modules = require(`../path/${myModule}`)
Run Code Online (Sandbox Code Playgroud)


Mik*_*ans 3

这是由于 Browserify 的捆绑方式所致,它只能进行静态字符串分析以进行需求重新绑定。因此,如果您想进行 browserify 捆绑,则需要对您的要求进行硬编码。

对于必须进入生产部署的代码(与快速原型相反,您很少费心为其添加捆绑),始终建议坚持静态需求,部分原因是捆绑,但也因为使用动态字符串为您提供您的要求意味着您正在编写不可预测的代码,因此可能充满您很少遇到的错误并且极难调试。

如果您根据不同的运行需要不同的要求(例如,开发、阶段测试与生产),那么通常最好使用process.env配置对象,这样当需要决定特定目的需要哪个库时,你可以使用类似的东西

var knox = config.offline ? require("./util/mocks3") : require("knox");
Run Code Online (Sandbox Code Playgroud)

这样,您的代码也可以立即供其他需要追踪问题出处的人访问,以防发现错误。