在requireJS中,后面定义一个命名模块不能覆盖之前的模块吗?

In requireJS, define a named module later cannot overwrite previous one?

代码如下

// When directly defining an AMD module in a browser, the module cannot be anonymous, it must have a name.

//If you are using the r.js optimizer you can define anonymous AMD modules and r.js will look after module names. This is designed to avoid conflicting module names.

// Define a module (export)
define('a', {
   run: function(x, y){
     return console.log(x + y);
   }
 });

define('a', {
   run: function(x, y){
     return console.log(x * y);
   }
 });

// Use the module (import)
require(['a'], function(a){
    a.run(1, 2);
});

require(['a'], function(a){
    a.run(4, 6);
});

这是 JsFiddle 上的演示:http://jsfiddle.net/NssGv/162/

结果是410,而不是224

让我意外的是后面的define不能覆盖前面的define。这是正常行为吗?有人对此有想法吗?

您必须在重新定义模块之前取消定义它:

define('a', {
    run: function(x, y){
        return console.log(x + y);
    }
});

requirejs.undef('a');

define('a', {
    run: function(x, y){
        return console.log(x * y);
    }
});

另请查看 requirejs.undef 的文档。