在browserify中要求不起作用变量名称 [英] Require in browserify doesn't work variable name

查看:73
本文介绍了在browserify中要求不起作用变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 require 使用传递给函数的变量的browserify文件:

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

var BackboneView = require(playersOptions.route.path);
//错误:未捕获错误:无法找到模块'playersOverview'

var BackboneView = require('playersOverview');
//需要文件没有任何问题。

我很困惑为什么会失败?当两者都是字符串时怎么能找不到模块?

解决方案

Browserify必须能够静态分析所有的需求语句在构建时,它可以知道它需要包含在包中的文件。这要求 require 只能与源代码中的字符串文字一起使用。



而不是传递名称稍后要求的模块,只需传递模块本身:

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

var BackboneView = playersOptions.route.module;

即使没有此Browserify限制(例如,如果您直接使用node.js) ,以后要避免传递模块名称仍然是个好主意,因为如果传递给它的模块名称有一个相对于调用者目录的路径并且被传递到不同目录内的文件中的代码,则require调用可能会中断。 / p>

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?

解决方案

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.

这篇关于在browserify中要求不起作用变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆