我可以获得 URL 一个 RequireJS 依赖映射到吗?

Can I get the URL a RequireJS dependecy maps to?

我可以得到 URL 一个 RequireJS 依赖映射到吗?

var foo = require('my-dependency');

我知道我的依赖项正在从 http://localhost/version/my-dependency.js 中删除。 RequireJS 是否公开了一个 API 来获取这个值?

您可以使用 require.toUrl("my-dependency") 获得一个 URL,它 相对于您当前的模块。例如,这应该输出一个相对的 URL:

define(function (require) {
  console.log(require.toUrl("my-dependency"));
});

你需要为此使用本地 require 以便 RequireJS 知道它是从哪个模块调用的。 (上面的依赖列表就不用了,如果不传递列表,RequireJS使用["require"、"module"、"exports"]的依赖列表。)

我不知道获得绝对 URL 的单步方法,但如果您需要绝对 URL,您可以结合 URL 提供的 [=14] =] 的 return 值为 require.toUrl:

define(function (require, module) {
  console.log(join(module.uri, require.toUrl("my-dependency")));
});

join 是一个能够连接 URL 的函数。您可以使用 URI.js、其他一些库,或者自己编写。)