Search code examples
javascriptrequirejsdurandal

Where does the module id come from in Durandal?


I'm working on a legacy app in durandal. I noticed when I define a module:

define({ message: 'hello world' });

Then the output from grunt looks like:

define('filePath\fileName',{ message: 'hello world' });

Where does filePath\fileName come from? I tried building a module in plain RequireJS and I had to supply this id myself. I read that Durandal uses a pattern called AMD (Asynchronous Module Definition pattern). Is the filePath\fileName using fileName.js convention a part of the AMD pattern?


Solution

  • AMD optimizers add these ids when they optimize your modules.

    As long as you have one module per file, an AMD loader is able to infer the module id from the path of the file and from the configuration of the module loader. So it is okay when you have one module per file to omit the module id from the define call, and let the AMD loader infer the module id. This is called an "anonymous define, by the way.

    One of the jobs of the optimizer is to combine multiple modules in a single file. When the optimizer combines multiple modules in the same file, then there's no way to distinguish which define call belongs to which module, unless the optimizer also records this information. The way the AMD specification is designed, the way to record which define belongs to which module is to add the module id as the first argument of define.