问题
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:
var part1_setup = requirejs( 'part1_setup' )
tells RequireJS to load yourpart1_setup1
module. Note here you are using a synchronous form of therequire
call (well, it's name isrequirejs
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 loads your module and executes it. Because you do not have an anonymous
define
in it (adefine
that does not specify a module name), the module loading fails. You need an anonymousdefine
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 printssetup
.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 againrequirejs([],...
is executed, which means the callback that printssetup
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