gpt4 book ai didi

javascript - 如何让用户访问 main 之外的 requirejs 模块?

转载 作者:行者123 更新时间:2023-11-30 10:19:09 25 4
gpt4 key购买 nike

我正在实现一个将在第三方网站上使用的面向 AMD 模块的 js 框架。

通过这一行,框架用户将配置必要的模块

<script data-main="/main.js" src="/require.js"></script>

问题是 data-main 引用是异步加载的,因此任何依赖 main.js 加载的模块的 js 逻辑都会失败,除非我可以确定它已完成加载中。

我对 requirejs 还很陌生,所以不确定创建一个供其他人使用的框架的最佳做法是什么。

如何解决这个非常简单的问题?

编辑一个例子来解释我的观点

ma​​in.js

requirejs.config({
paths: {
jquery: '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min',
}
});

主要 js 引用 + 额外代码

 <script data-main="/main.js" src="/require.js"></script>
<script>
require(['jquery'], function($) {
// since main.js is not loaded yet, it will assume that there is a jquery.js
// file on the same folder that this file
console.log('myModule was also loaded and can use jQuery');
});
</script>

最佳答案

如果你想依赖其他库并且特别针对在 Require 管道中,你需要做的就是用

声明一些依赖项
define(
'myModule', // module name
['foo'], // module dependencies
function(foo){ // module construction
var myModule = {};

.... code to set up the module ....

return myModule;
});

并且 Require 会处理事情。这将使用 Require 注册您的模块,并且在您的所有依赖项都可用之前不会尝试构建您的模块。讨论了此功能 here .

用例子更新

Require JS 被设计为可以在有和没有预构建配置的情况下工作。 Require 配置对象的 paths 属性仅向 Require 提供有关如何尝试查找尚未注册的库的信息。但是,无论模块是如何/在何处注册的,注册和依赖解析都是由 Require 处理的。请看this JSFiddle有关您如何注册和使用依赖项的工作示例。

关于配置的更新 2

由于 RequireJS 异步加载所有内容,您是正确的,您的代码示例将无法运行。但是,您对它“应该”如何工作做出了错误的假设。您有一个不正确的示例,说明您的图书馆客户的 Require 配置将是什么样子。如果其他人正在使用 RequireJS 构建应用程序并且他们想要使用您的库,他们应该在他们的 require.config 中声明您的库的路径:

require.config({
paths: {
// this tells require how to load jQuery (a library maintained neither by you nor your clients).
'jquery': '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min',
// this tells require how to load myModule (the library you are building for your clients).
'myModule': '//example.com/js/my-module.min',
// this tells require how to load foo (a library built and hosted by your clients).
'foo': 'scripts/foo'
}
});

另一方面,如果您的客户不能更新他们的 Require 配置以在声明中包含您的库,那么您就不走运了。您所能做的就是获取所有依赖项并将它们捆绑在分发文件中,然后声明没有依赖项:

define(
'myModule',
[], // can't declare any dependencies
function() {
// these dependencies are inside of the definition function to keep the global namespace clean
// since we need jQuery, we have to inline it:
var jQuery = ....
// same goes for d3.js
var d3 = ....

// now we can set up the module itself
var myModule = {};
.... code to set up the module ....
return myModule;
}
);

显然,这个选项意味着您不能使用您的客户正在使用的库。这意味着您的库会更重,并且包含有效的重复代码和数据。

希望这能帮助您了解 Require 的工作原理以及其他人将如何使用您的库。

关于javascript - 如何让用户访问 main 之外的 requirejs 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22204882/

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