简体   繁体   English

为什么我不能在 node.js (browserify) 的 require() 函数中使用变量作为参数?

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

I tried something like:我试过类似的东西:

var path = '../right/here';
var module = require(path);

but it can't find the module anymore this way, while:但它无法再通过这种方式找到模块,而:

var module = require('../right/here');

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.想使用生成的字符串列表加载模块,但我无法解决这个问题 atm。 Any ideas?有任何想法吗?

you can use template to get file dynamically.您可以使用模板动态获取文件。

var myModule = 'Module1';
var Modules = require(`../path/${myModule}`)

This is due to how Browserify does its bundling, it can only do static string analysis for requirement rebinding.这是由于 Browserify 的捆绑方式,它只能对需求重新绑定进行静态字符串分析。 So, if you want to do browserify bundling, you'll need to hardcode your requirements.因此,如果您想进行 browserify 捆绑,则需要对您的需求进行硬编码。

For code that has to go into production deployment (as opposed to quick prototypes, which you rarely ever bother to add bundling for) it's always advisable to stick with static requirements, in part because of the bundling but also because using dynamic strings to give you your requirements means you're writing code that isn't predictable, and can thus potentially be full of bugs you rarely run into and are extremely hard to debug.对于必须进入生产部署的代码(与快速原型相反,您很少费心为其添加捆绑)始终建议坚持静态需求,部分原因是捆绑,但也因为使用动态字符串为您提供您的要求意味着您正在编写不可预测的代码,因此可能充满了您很少遇到且极难调试的错误。

If you need different requirements based on different runs (say, dev vs. stage testing vs. production) then it's usually a good idea to use process.env or a config object so that when it comes time to decide which library to require for a specific purposes, you can use something like如果您需要基于不同运行的不同要求(例如,开发与阶段测试与生产),那么使用process.env或配置对象通常是个好主意,以便在决定需要哪个库时具体目的,你可以使用类似的东西

var knox = config.offline ? require("./util/mocks3") : require("knox");

That way your code also stays immediately traversable for others who need to track down where something's going wrong, in case a bug does get found.这样,您的代码也可以立即被其他需要追踪哪里出错的人遍历,以防确实发现了错误。

require('@/path/'.concat(fileName))

您可以使用.require()添加要访问的文件,计算其路径而不是在构建时是静态的,这样这些模块将被包含在内,并且稍后调用require()时会找到它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM