0
votes

I'm trying to better understand requirejs and have a question on how define() works. I have a simple html page the loads requirejs via the following script tag.

<script data-main="scripts/main.js" src="scripts/require.js"></script>

main.js contains:

console.log("in main");
require.config({
  baseUrl: 'scripts'
});

define('temp_module', ['module3'], function(t) {
  console.log("ta: ", t);
  return {
    "sundry": t.input
  }
});

module3.js contains:

define(function() {

  return {
    input: "output"
  }
});

What I expected is the the define statement will define and cache a new module named 'temp_module' depending on what is returned from the callback function. The callback function takes in the return value of module3. At this point both temp_module and module3 are cached if needed later.

Clearly that is not how this is supposed to behave as I only get the "in main" output in the console and not the console.log from the callback function.

Can anyone correct my understanding on how this should work?

Thanks.

2

2 Answers

0
votes

A defined module is not "loaded" until it's required (included) by someone.

In your main.js just do:

require([ 'module3' ], function (module3) {
  ...
});

Also, avoid giving explicit names to your modules yourself (like "temp_module") unless you have a specific reason to. Let RequireJS give modules names based on their paths.

0
votes

The missing piece is that you do not have anything that requires the loading of temp_module. When RequireJS processes data-main="scripts/main.js" it is looking for a module named main. It finds your file scripts/main.js, and executes it but there is no module named main in it, so the loading ends right there.

You could change the name of temp_module to main, or remove the name entirely, and then it should work.

When you remove the name, what you have is an anonymous define call. RequireJS allows one anonymous define call per file. An anonymous define call gets a module name associated with it at loading time. RequireJS uses the module name that was used when the module was requested and associates this name to the define. In your case the name would be main. This is because your module is required through the data-main attribute, and this attribute is subject to some special handling because it has to serve to provide both a path to load a module and an initial module name. When RequireJS processes your data-main value, it uses that value literally to determine path to load. However, it makes a module name by dropping the .js and by keeping only the last part of the path so from scripts/main.js it gets the module name main. Then it loads the file at the path and looks for the module named main in your file. Since there is only a single anonymous define, it takes that define as defining the main module and calls the callback.