【问题标题】:requirejs + bower, paths and dependencies within bower components需要js + bower,bower组件中的路径和依赖项
【发布时间】:2015-03-06 01:53:04
【问题描述】:

我做了很多研究,但找不到我正在寻找的答案,所以这里。

我有一个 bower 组件,它有自己的依赖项:

/vendor/bower_components/my_module/my_module.js /vendor/bower_components/my_module/dependency_1.js /vendor/bower_components/my_module/dependency_2.js

在 my_module.js 内部,它使用相对路径加载其依赖项:

define(["./dependency_1", "./dependency_2"], function (dep1, dep2) { ... });

但是当我的 requirejs config.paths 设置好时:

paths: {
    my_module: "/vendor/bower_components/my_module/my_module"
}

... 现在相对路径是相对于基本 requirejs 路径而不是 my_module 的完整路径。我明白为什么会发生这种情况(因为模块 id 不再是完整路径,而是缩短的名称),我只是不知道如何解决它。我很确定包裹是正确的方向,我只是没有运气。我该怎么办? my_module 是第三方模块顺便说一句,宁愿不编辑它。谢谢。

更新 - 我的应用程序中的代码使用示例:

场景 1(没有config.paths):

define(["/vendor/bower_components/my_module/my_module"], function(myModule) {
    // This works.  No issues here.
    // The reason this works is because the module ID for myModule is:
    // "/vendor/bower_components/my_module/my_module"
    // Therefore, the relative paths "./dependency_1" and "./dependency_2"
    // are resolved against that module ID.
});

场景 2 - 现在 my_module 在 config.paths 中定义(见上文):

define(["my_module"], function(myModule) {
    // Error, cannot load files dependency_1.js or dependency_2.js
    // This is because relative paths are resolved against a module's ID.
    // Now the module ID is "my_module", not "/vendor/bower_components/my_module/my_module"
    // As such, the paths for ./dependency_1 and ./dependency_2 are resolved against "/"
});

不幸的是(或不是?)这是设计使然:http://requirejs.org/docs/api.html#modulenotes-relative-names。我们应该能够使用包来解决这个问题。我只是想知道是否有人知道如何做到这一点。

【问题讨论】:

  • 抱歉,我的英语可能不太好,但是……请问有什么问题?我只是尝试阅读它几次,但没有关于您的问题的线索。好像没有运行?或者你遇到了什么问题?
  • 我更新了我的问题。让我知道这是否更有意义。谢谢。

标签: javascript requirejs bower amd


【解决方案1】:

这就是我到目前为止对您的问题的了解。您可以使用这些配置做您想做(或不做?)的事情:

require.config({
    packages: [
        {
            name: "myModule"
            location: '/vendor/bower_components/my_module/',
            main: "my_module"
        }
        // [name option] can be anything you want
        // [main option] pointing to your main js file of the package
        // if you rename your mymodule.js to main.js you no longer need to config the [main option]
    ]
});

在你的 my_module.js 中

define(["./dependency_1", "./dependency_2"], function (dep1, dep2) {
  // ...
});

你可以像这样调用你的 my_module.js。

define(["myModule"], function(myModule) {
    // ...
});

欲了解更多信息,您可以查看此链接Common-config#packages

【讨论】:

  • 嘿,谢谢。如果我有时间,我会在星期一测试它。主要问题是我无法更新 my_module 的代码。在我的示例中,我应该将其命名为 someone_elses_module,但这太罗嗦了。不过,您的解决方案似乎步入正轨。
  • 希望对您有所帮助:)
  • 工作就像一个魅力。谢谢一堆。值得注意的是my_module 是一个标准的 AMD 库而不是 CommonJS 库。 requirejs 文档暗示包应该用于 CommonJS 库......但它可以用于任何东西。
猜你喜欢
  • 2013-08-18
  • 2014-10-26
  • 2013-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多