gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:00:53 24 4
gpt4 key购买 nike

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

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com