Search code examples
javascriptrequirejsamdcommonjs

RequireJS with CommonJS modules


Using RequireJS with CommonJS modules, what happens when I do this:

define(function(require, exports, module) {
    //Put traditional CommonJS module content here

    var simpleCommonJSModule = require('simple-commonjs-module');   

    module.exports = new String('foo');

   return {
        //return empty object along with using module.exports
   }
});

if I return something, I assume the module.exports will be ignored? Or is it the other way around?


Solution

  • Yes, if you return something module.exports will ignored.

    Here's a snippet from the original documentation.

    define(function(require, exports, module) {
           var a = require('a'),
               b = require('b');
    
           //Return the module value
           return function () {};
        } 
    );
    

    If you want to use the exports CJS style here's you do it

    define(function(require, exports, module) {
       exports.foo = function () {
           return a.bar();
       };
    });