Browserify:通过字符串连接创建的路径要求 js 文件时出现未捕获错误
Browserify: Uncaught error when requiring js file by path created from string concatenation
我正在为客户端应用程序使用 browesify。我有文件 maps.js
和 directions.js
坐在我的 index.js
文件旁边,在我的 index.js
里面,我有一个函数 getPageName()
其中 returns 名字我应该 "require" 的文件。当我尝试做
var pageName = getPageName();
var page;
if (pageName === 'maps') {
page = require('./maps');
} else if (pageName === 'directions') {
page = require('./directions');
}
它工作正常。但是当我尝试使用以下技巧来最小化我的代码时,
var pageName = getPageName();
var page = require('./' + pageName);
我在 Chrome 的控制台登录中收到错误 Uncaught Error: Cannot find module './maps'
。为什么当我使用字符串连接时它不起作用,但当我使用显式传递路径时它起作用?
这是 Browserify 和类似类型库的限制。为了执行 require()
,库必须将 js 代码作为字符串进行检查,并在代码 运行 之前确定文件路径。这意味着文件路径必须是静态的才能被拾取。
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
我正在为客户端应用程序使用 browesify。我有文件 maps.js
和 directions.js
坐在我的 index.js
文件旁边,在我的 index.js
里面,我有一个函数 getPageName()
其中 returns 名字我应该 "require" 的文件。当我尝试做
var pageName = getPageName();
var page;
if (pageName === 'maps') {
page = require('./maps');
} else if (pageName === 'directions') {
page = require('./directions');
}
它工作正常。但是当我尝试使用以下技巧来最小化我的代码时,
var pageName = getPageName();
var page = require('./' + pageName);
我在 Chrome 的控制台登录中收到错误 Uncaught Error: Cannot find module './maps'
。为什么当我使用字符串连接时它不起作用,但当我使用显式传递路径时它起作用?
这是 Browserify 和类似类型库的限制。为了执行 require()
,库必须将 js 代码作为字符串进行检查,并在代码 运行 之前确定文件路径。这意味着文件路径必须是静态的才能被拾取。
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