运行以下代码的节点输出是:
all Loaded
dbModule undefined
mongoose loaded
我在appMod2中获取对dbMod2的引用时遇到问题。我该怎么办?
//server.js
var requirejs = require( 'requirejs');
process.on( 'uncaughtException', function(error) {
console.log( 'Exception ' + error.stack);
process.exit( 1);
});
requirejs.config({
baseUrl: '.',
nodeRequire: require
});
requirejs(['./appMod2'], function() {
console.log( "all Loaded");
})
// appMod2.js
require(['./dbmod2'], function( dbmodule) {
console.log( "dbModule " + dbmodule);
});
// dbmod2.js
require(['mongoose'], function( mongoose) {
Schema = mongoose.Schema;
console.log( "mongoose loaded");
});
答案 0 :(得分:0)
用'define'替换'require'调用并将return语句添加到模块中:
// dbmod2.js
define(['mongoose'], function( mongoose) {
Schema = mongoose.Schema;
console.log( "mongoose loaded");
return 'dbmod2';
});
// appMod2.js
define(['./dbmod2'], function( dbmodule) {
console.log( "dbModule " + dbmodule);
return 'appMod2';
});
我得到了这个输出:
mongoose loaded
dbModule dbmod2
all Loaded
在requirejs中,传递给依赖项数组后面的函数的对象是依赖项返回的对象