Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require in browserify doesn't work variable name

I am trying to require a file with browserify using variables passed into a function:

var playersOptions = {
    name: 'players',
    ajax: 'team-overview',
    route: {
        name: 'overview',
        path: 'playersOverview',
        url: 'playersoverview'
    }
 };

var BackboneView = require(playersOptions.route.path); 
//Error: Uncaught Error: Cannot find module 'playersOverview'

var BackboneView = require('playersOverview');
//Requires the file without any problems.

I am confused as to why this would fail? How can it not find the module when both are strings?

like image 587
Jamie Hutber Avatar asked Oct 17 '14 22:10

Jamie Hutber


1 Answers

Browserify has to be able to statically analyze all of the require statements at build time so it can know what files it needs to include in the bundle. That requires that require can only be used with a string literal in the source code.

Instead of passing the name of a module around to require later, just pass the module itself:

var playersOptions = {
    name: 'players',
    ajax: 'team-overview',
    route: {
        name: 'overview',
        module: require('playersOverview'),
        url: 'playersoverview'
    }
 };

var BackboneView = playersOptions.route.module;

Even if this Browserify limitation wasn't present (eg. if you were using node.js directly), it's still a good idea to avoid passing module names to be required later because the require call could break if the module name passed to it had a path relative to the caller's directory and was passed into code in a file inside a different directory.

like image 89
Macil Avatar answered Sep 20 '22 14:09

Macil