javascript - requirejs + bower,bower 组件中的路径和依赖项

标签 javascript requirejs bower amd

我已经做了很多研究,但找不到我正在寻找的答案,所以就这样吧。

我有一个 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 不再是完整路径,而是缩短的名称),我只是不知道如何解决它。我很确定 packages 是正确的方向,我只是运气不好。我该怎么办? 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 .我们应该能够使用包来解决这个问题。我只是想知道是否有人知道如何执行此操作。

最佳答案

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

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

关于javascript - requirejs + bower,bower 组件中的路径和依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28891141/

相关文章:

javascript - 使用 RequireJS 加载其他地方不需要的文件

jquery - Gulp 不注入(inject) jquery ui 主题 css

javascript - 处理:仅在第一次激活 mousePressed() 时不会打印文本

javascript - jQuery UI Slider 在按下时奇怪地跳跃

angularjs - 使用深度链接刷新 html 模式 Angular 应用程序

asp.net-mvc - 我应该使用 RequireJS 或 ASP.NET 捆绑,还是两者都使用

github - 如何使用 Bower 正确注册 github 分支

git - 将 repo 的子目录作为 github 中的不同 repo

javascript - AngularJS 指令中的重复样式属性

javascript - 在 React Native 中导入外部 js 文件时,undefined 不是对象