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

落爺英雄遲暮 提交于 2019-12-12 15:39:02

问题


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


回答1:


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.

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.




回答2:


You can use .require() to add the files that you want to access calculating its path instead of being static at build time, this way this modules will be included and when calling require() later they will be found.



来源:https://stackoverflow.com/questions/29051921/why-can-i-not-use-a-variable-as-parameter-in-the-require-function-of-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!