Isomorphic JavaScript with RequireJS

155 views Asked by At

I have some isomorphic JavaScript. I am using RequireJS on the client side.

(function() {
    'use strict';

    function wrapper(require) {
      var MyDep = require('my-dependency');

      return function MyExportedFunction() {
          // ...
      };
    }

    if ((typeof exports === 'object') && module) {
        module.exports = wrapper(require); // CommonJS
    } else if ((typeof define === 'function') && define.amd) {
        define(function(require) {
            /**
             * I need to `require` dependencies 
             * in here for them to be available inside 
             * the wrapper function :(
             */
            require('my-dependency');
            return wrapper(require);
        }); // AMD
    }
}());

Is there a way to circumvent having to place the require statment positioned immediately before the wrapper function invocation?

If I omit that require statement, RequireJS complains that the dependency has not yet been loaded for the context.

I presume this is an insurmountable limitation of RequireJS' ability to parse and identify require'd dependencies ahead of time.

1

There are 1 answers

0
Louis On BEST ANSWER

Yeah, RequireJS can only handle the CommonJS form of require only if it is present immediately in the factory function passed to define. If it appears in functions called from the factory function but that are defined outside the function, then it won't work. Internally, RequireJS runs a regular expression on the factory function's source.

This being said, it seems to me you should be able to replace your current call to define with:

define(wrapper)

This will call wrapper with a reference to RequireJS' require function and RequireJS should be able to analyze the source of wrapper to extract the CommonJS calls.