nopuck4you suggests that you add the module name as the first argument of the define
call. If these modules are created inside of a <script>
tag right inside your HTML, then that's okay. This is one of the rare exceptions where you can put a module name as the first argument of define
. Actually, in this kind of situation you have to name the modules otherwise RequireJS cannot find them. So you'd have:
<script>
define("foo", ["testcode"], function(testcode){
window.foo = "bar";
});
define("test", ["foo"], function(){
alert(window.foo); // "bar"
});
</script>
(I've assumed that the 2nd module depends on the 1st and named things accordingly. I don't know what the testcode
thing is so I left it as is.)
However, in general, you should not give names to modules by putting the name in the define
call. The RequireJS documentation is quite clear about this. If you do name your modules in the define
, this may cause issues down the road due to the way RequireJS works. Things will not work, or they won't work unless you work around the problem. For instance, if you put modules foo
and bar
in foo.js
and put their names as the first argument of define
, RequireJS won't have any trouble figuring that module foo
is in foo.js
but it won't know right off the bat that bar
is also in foo.js
. Depending in which order you load your modules, you might have to have additional configuration telling RequireJS that bar
is in foo.js
.
Putting the names of your modules in the define
calls just leads to failures, surprises, complications, etc. Don't do it. Leave the name out and let RequireJS figure it out. Then, when you optimize, let r.js
put the names in.
Note: you may have seen some code from 3rd parties that have the module names put right into the define
. jQuery is a prominent case. There are exceptions to what I said above but if you cannot articulate a substantial reason why you need to put the name in, then you don't need to do it. (In fact, looking at the jQuery case, I don't see a good reason to put the name in the define
there and in my opinion they made a mistake.)