gpt4 book ai didi

javascript - 需要在另一个脚本中定义的模块

转载 作者:行者123 更新时间:2023-12-03 08:34:40 28 4
gpt4 key购买 nike

脚本A

;(function(g){

define('hotness', [], function() {
function f() {;
console.log('gotem');
}
return f;
});

define('otherModule', [], function() {});


})(this);

脚本B

define([
'ScriptA',
], function() {

var hotness = require('hotness')
});

错误:尚未为上下文加载模块名称“hotness”:_

在 ScriptB 中的 ScriptA 定义中推荐的 require 方式是什么?

我也尝试过:

脚本 B Alt

define([
'require',
'ScriptA',
'hotness'
], function(require) {

var hotness = require('hotness')
});

这给了我

加载资源时出错.../hotness.js:没有这样的文件或目录
错误:脚本错误:hotness

编辑:

需要注意的是,ScriptA 保持原样并且不会被修改。问题是如何从 ScriptB 获取 ScriptA 中的命名模块。

编辑2:

我无法控制 HTML 或页面的任何其他方面。我必须在 ScriptB 内完成所有操作。

编辑3:

我有一个可行的例子,但它看起来像是一个可怕的反模式解决方法,所以我什至不想提及它:

define(['require'], function(require) {
// why use window? IDK.
// this is just verbatim what is "working" for someone else
window.require(['scriptA'], function(sA) {
//sA never actually used
window.require([
'otherModule'
], function(oM) {
var hotness = require('hotness'),

最佳答案

您应该使用 bundles configuration 。鉴于您所描述的工作原理,您应该使用:

bundles: {
'scriptA': ['hotness', 'otherModule']
}

这本质上告诉RequireJS“当你想找到hotnessotherModule时,然后加载scriptA,因为它们是在那里定义的”。我时常使用它从使用 r.js 生成的包中加载模块。

除此之外Joseph the Dreamer正确的是,您不应在同一模块中混合使用 AMD 和 CommonJS 方法来获取依赖项。

关于javascript - 需要在另一个脚本中定义的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33246019/

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