Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  109] [ 7]  / answers: 1 / hits: 5073  / 11 Years ago, mon, january 27, 2014, 12:00:00

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:




More From » node.js

 Answers
10

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.


[#48334] Saturday, January 25, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianom

Total Points: 601
Total Questions: 98
Total Answers: 109

Location: Kenya
Member since Fri, Dec 23, 2022
1 Year ago
lucianom questions
Tue, Feb 22, 22, 00:00, 2 Years ago
Wed, May 5, 21, 00:00, 3 Years ago
Sun, Jan 24, 21, 00:00, 3 Years ago
Sat, Aug 15, 20, 00:00, 4 Years ago
Mon, Jun 22, 20, 00:00, 4 Years ago
;