代码>.You have to replace your requirejs call in your part1_setup.js with define.当你在 node 中使用 RequireJS 时,有一个特殊性:如果 RequireJS 自己加载模块失败,它会尝试让 Node 的 require 加载模块.以下是您的代码发生的情况:When you use RequireJS in node, there's a peculiarity: if RequireJS fails to load a module by itself, it will try to get Node's require to load the module. Here's what happens with your code:var part1_setup = requirejs('part1_setup') 告诉 RequireJS 加载你的 part1_setup1 模块.注意这里你使用的是 require 调用的同步形式(好吧,它的名字是 requirejs 但它实际上是 RequireJS 的 require 调用).在浏览器中,这种调用不是真正同步的(并且您的特定调用会失败),而在 Node 中它是真正同步的.var part1_setup = requirejs( 'part1_setup' ) tells RequireJS to load your part1_setup1 module. Note here you are using a synchronous form of the require call (well, it's name is requirejs but it is really RequireJS' require call). Whereas in a browser such call is not really synchronous (and your specific call would fail), in Node it is truly synchronous.RequireJS 加载您的模块并执行它.由于其中没有匿名 define(未指定模块名称的 define),模块加载失败.你需要一个匿名的 define 为 RequireJS 确定它应该运行什么工厂函数,以便定义模块.但是,文件中的代码 是 执行的,因此您告诉 RequireJS当依赖项 [] 加载后,然后执行我的回调".没有什么可加载的.RequireJS 执行打印 setup 的回调.RequireJS loads your module and executes it. Because you do not have an anonymous define in it (a define that does not specify a module name), the module loading fails. You need an anonymous define for RequireJS to determine what factory function it should run so that the module is defined. However, the code in the file is executed so you are telling RequireJS "when the dependencies [] have loaded, then execute my callback". There is nothing to load. RequireJS executes the callback that prints setup.这是在 Node 中运行 RequireJS 的特殊之处: 由于模块加载失败,RequireJS 会使用您的模块名称调用 Node 的 require 函数.Node 查找模块并加载它.所以Node再次执行文件中的代码,再次执行requirejs([],...,这意味着打印setup的回调再次运行.This is special to running RequireJS in Node: Because the module loading failed, RequireJS then calls Node's require function with your module name. Node looks for the module and loads it. So Node executes the code in the file a second time, and again requirejs([],... is executed, which means the callback that prints setup runs again.您应该始终在模块文件中使用 define 而不是 require(或 requirejs)调用.You should always have a define in your module files rather than a require (or requirejs) call. 这篇关于节点中的Requirejs无缘无故执行两次调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 13:41