Javascript 如何使用RequireJS获取脚本URL?

Javascript 如何使用RequireJS获取脚本URL?,javascript,requirejs,Javascript,Requirejs,在加载带有标记的脚本时,您可以如下方式检索脚本URL: var scriptURL = Array.prototype.pop.call ( // get the last... document.getElementsByTagName ('script') // ...script tag on the page... ).src.split ('?') [0]; // ...take 'src' attribu

在加载带有
标记的脚本时,您可以如下方式检索脚本URL:

var scriptURL = Array.prototype.pop.call (       // get the last...
        document.getElementsByTagName ('script') // ...script tag on the page...
    ).src.split ('?') [0];                       // ...take 'src' attribute...
                                                 // ...and strip the query string
这是一个小技巧,但有时可能非常有用,原因有很多(例如,当脚本依赖于其他资源文件并且您不想硬编码路径时)。它之所以有效,是因为在执行时,页面上存在的最后一个
标记是您的脚本


我不确定在加载带有RequireJS的脚本时是否如此。在RequireJS中是否有类似的方法从模块定义内部检索脚本URL?

您可以要求
模块
模块,该模块通常用于传递特殊设置:

define(['module'], function (module) {
  console.log(module)
}

这将为您提供一个包含模块id和uri的对象,以获取当前模块的URL,您可以在requirejs中使用下面的脚本

define([module/hello], function (hello) {
    var currentUrl = location.href;
    var moduleUrl = url+require.toUrl("module/hello.js");
    alert(moduleUrl);
});