Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 345
rumbledore Avatar asked Mar 14 '15 17:03

rumbledore


3 Answers

you can use template to get file dynamically.

var myModule = 'Module1';
var Modules = require(`../path/${myModule}`)
like image 133
Gaurav Vanani Avatar answered Oct 09 '22 03:10

Gaurav Vanani


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.

like image 45
Mike 'Pomax' Kamermans Avatar answered Oct 09 '22 03:10

Mike 'Pomax' Kamermans


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

like image 27
Shivang Trivedi Avatar answered Oct 09 '22 04:10

Shivang Trivedi