Hanfei Sun
Hanfei Sun

Reputation: 47051

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

Following is the code

// 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);
});

Here is the demo on JsFiddle: http://jsfiddle.net/NssGv/162/

The result is 4 and 10, instead of 2 and 24.

What looks unexpected to me is that the later define can't overwrite the previous define. Is this a normal behavior? Does anyone have ideas about this?

Upvotes: 3

Views: 1074

Answers (1)

mario.van.zadel
mario.van.zadel

Reputation: 2949

You have to undefine the module before redefining it:

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);
    }
});

Please also check the documentation of requirejs.undef.

Upvotes: 1

Related Questions