javascriptrequirejsrequirejs-optimizer

requirejs optimizer just define module name only


I want to use requirejs optimizer just to create/define the module name for my js file.

eg : if i have a file say test.js under modules/moduleA

modules
|
|
-----moduleA
     |
     -----test.js

i want requirejs optimizer to create just the module name for me based on path...eg below I want requirejs optimizer to create the module name modules/moduleA/test and put inside the define present in the test.js

Eg: Before running requireJS optimizer

test.js content:

define( ["my/cart", "my/inventory"],
            function(cart, inventory) {
               ...
           }
        );

After running requirejs optimizer

test.js content

define("modules/moduleA/test",
            ["my/cart", "my/inventory"],
            function(cart, inventory) {
               ...
           }
        );

I Will take care of combining the related dependent files later by means of grunt ...but i want requirejs optimizer to visit each file and give me the module name based on path it presents.

Is this feasible?


Solution

  • James Burke the author of Requirejs provided an answer to this via another forum.

    We can easily do this via using transform from RequireJS:

    var requirejs = require('requirejs');
    requirejs.tools.useLib(function(require) {
      require(['transform'], function (transform) {
         //todo: generate a files array with the list of files to concatenate.
    
          files.forEach(function(filePath) {
            var fullPath = path.join(targetDir, filePath);
            var contents = fs.readFileSync(fullPath, 'utf8');
            var moduleId = /* todo, figure out what the moduleId is for the module */
            var transformed = transform
                              .toTransport('', moduleId, fullPath, contents);
    
            //todo: concat the contents together
          });
        });
      });
    });