为什么不能在node.js(browserify)的require()函数中将变量用作参数? [英] Why can I not use a variable as parameter in the require() function of node.js (browserify)?

查看:119
本文介绍了为什么不能在node.js(browserify)的require()函数中将变量用作参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过以下操作:

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. Any ideas?

推荐答案

这是由于Browserify如何进行捆绑,它只能对需求重新绑定进行静态字符串分析。因此,如果要进行浏览器捆绑,则需要对要求进行硬编码。

This is due to how Browserify does its bundling, it can only do static string analysis for requirement rebinding. So, if you want to do browserify bundling, you'll need to hardcode your requirements.

对于必须投入生产部署的代码(与快速原型相反,建议您始终坚持使用静态需求,这在某种程度上总是建议您坚持使用静态需求,部分原因是因为存在捆绑,而且还因为使用动态字符串来满足您的需求意味着您正在编写不可预测的代码,并且可以因此,可能充满了您很少会遇到且很难调试的错误。

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.

如果您需要基于不同运行的不同需求(例如,开发与阶段测试, (生产),那么通常最好使用 process.env 或配置对象,以便在需要确定特定用途的库时,您可以使用类似的

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

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.

这篇关于为什么不能在node.js(browserify)的require()函数中将变量用作参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆