Question

How can I make the node.js require function in pure JavaScript? I have searched the web for any solutions but I have found none.

Something along the lines of this:

function require(path){
    //Code
    return data;
}

Some of the posts I have already seen:

Was it helpful?

Solution

CommonJS functionality is implemented in the Curl Library As pointed out in other answers RequireJS follows the AMD spec which is different than Node's CommonJS var foo = require('foo'); spec.

Curl Features at a glance:

  • Loads AMD-formatted javascript modules in parallel
  • Loads CommonJS/node modules (v1.1 when wrapped in a define())
  • Loads CommonJS/node modules (unwrapped when using the cjsm11 loader)
  • Loads non-AMD javascript files in parallel, too.
  • Loads CSS files and text files in parallel
  • Waits for dependencies (js, css, text, etc) before executing javascript
  • Waits for domReady, if desired
  • Allows for virtually limitless combinations of files and dependencies
  • Tested with Safari 5+, IE6+, and recent Chrome, FF, Opera

Browserify does not implement CommonJS straight out but rather transpiles your CommonJS style code into a single bundle.js file which is included in the html.

Webmake seems to offer similar functionality to Browserify while also allowing for other file types.

In a nutshell CommonJS works like this:

  1. Maintain a map of identifiers that correspond to loaded modules.
  2. When a require('lib')is encountered, check the list to see if it has been loaded. If the library has not been loaded (it's key is not in the library), load the script via XHRRequest. If the library has been loaded, return the value that corresponds to the key.

This is why required modules are always singletons.

OTHER TIPS

RequireJS uses AMD loader, whereas node.js uses CommonJS pattern loading.

Browserify allows you to wrap up all of your code in a build step so you can have require() statements in a browser.

To roll your own (which I do not suggest, as Browserify is already a battle-tested, popular library), you would have to map all of your modules on your own and load it upfront, or load them synchronously (as that's necessary for CommonJS spec), in a blocking (and undesirable) way.

code in your function should contain full module resolution logic, which may not be that light and simple. You can check source code of module module which is responsible for that in node.js -> https://github.com/joyent/node/blob/master/lib/module.js

There are various tools which help you port CJS modules outside of node.js (they provide require function for you): Most popular is Browserify, but you can also check Webmake (I'm the author).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top