Why can I not use a variable as parameter in the require() function of node.js (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.

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.


you can use template to get file dynamically.

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