Requirejs in node executing call twice for no reason?

喜欢而已 提交于 2020-01-17 03:42:08

问题


Trying to get my head around using requirejs in node, when I run a sync call as described in the RequireJS in Node manual with the following...

//Retrieves the module value for 'a' synchronously
var a = requirejs('a') )

However when I've tried this approach it executes the request twice?

part0_start.js...

var requirejs = require('requirejs');
requirejs.config({
    nodeRequire : require 
});
var part1_setup = requirejs( 'part1_setup' ) 
console.log( 'part1_setup complete')

part1_setup.js...

requirejs([], function() {
    console.log( 'setup');
})

this should output...

setup
part1_setup complete

but instead it outputs...

setup
setup
part1_setup complete

Can anyone enlighten me please?


回答1:


You have to replace your requirejs call in your part1_setup.js with define.

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:

  1. 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.

  2. 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.

  3. 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.

You should always have a define in your module files rather than a require (or requirejs) call.



来源:https://stackoverflow.com/questions/31039014/requirejs-in-node-executing-call-twice-for-no-reason

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!