Require in browserify doesn't work variable name

情到浓时终转凉″ 提交于 2019-11-30 01:25:34

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/26434214/require-in-browserify-doesnt-work-variable-name

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