RequireJS:每次导入模块或刚刚第一次执行模块功能?

Ben*_*rts 2 javascript requirejs

我意识到我可以通过一个简单的测试项目来回答自己(我可能会,如果没有一个人立刻响起),但我无法在SO或谷歌的任何地方找到答案,这似乎很关键:

如果我用require.js定义一个AMD模块:

//a.js
define( ['stuff'], function (Stuff) {
     return { thing: new Stuff() };
}
Run Code Online (Sandbox Code Playgroud)

然后我在两个不同的其他模块中使用它:

// b.js
define( ['a'], function(a) {
    // do something with a's stuff 
});

// c.js
define( ['a'], function(a) {
  //do something else with a's stuff
}
Run Code Online (Sandbox Code Playgroud)

每当我为另一个模块需要它时,是否a定义函数被调用(因此是一个新Stuff实例化的),或者它只被调用一次,它的输出是否被缓存?

显然,这在一些用例中很关键,但从require.js文档或我见过的其他示例中并不清楚.

Cle*_*usW 7

我自己测试了这个,看起来构造函数只运行一次.

// stuff.js
define(function() {
    return function() {
        console.log('making new!');
    };
});

// a.js
define( ['stuff'], function (Stuff) {
     return { thing: new Stuff };
});

// b.js
define( ['a'], function(a) {
});

// c.js
define( ['a'], function(a) {
});

// app.js
define(['b', 'c'], function() {
    console.log('app');
});

// index.html
<html>
<head>
    <script src='requirejs/require.js' data-main='app.js'></script>
</head>
</html>
Run Code Online (Sandbox Code Playgroud)

当我打开index.html时,控制台显示:

making new!                             stuff.js:3
app                                       app.js:2
Run Code Online (Sandbox Code Playgroud)