0

I am using browesify for client side app. I have files maps.js and directions.js sitting besides my index.js file, and inside my index.js, I have a function getPageName() which returns the name of the file that I should "require". When I try to do

var pageName = getPageName();
var page;
if (pageName === 'maps') {
    page = require('./maps');
} else if (pageName === 'directions') {
    page = require('./directions');
}

it works fine. But when I instead try to use following trick to minimize my code,

var pageName = getPageName();
var page = require('./' + pageName);

I get error Uncaught Error: Cannot find module './maps' in console log in Chrome. Why does it not work when I use string concatenation but works when I use pass the path explicitly?

1 Answer 1

1

That is a limitation of Browserify and similar type libraries. In order to do the require() the library has to examine the js code as a string, and determine file paths before the code is run. This means file paths have to be static in order for it to be picked up.

https://github.com/substack/node-browserify/issues/377

Browserify can only analyze static requires. It is not in the scope of browserify to handle dynamic requires

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.