How to use JS require () without Node.js

This is probably a lame question, but how can you achieve the same as require() (Node.js) in regular JavaScript?

Some help would be really appreciated.

+6
source share
2 answers

There are several services that allow you to do this.

The most popular is Browserify .

Basically, this involves viewing the file through the syntax tree and converting it to a style similar to what RequireJS requires.

Please note that this requires an additional compilation step. (We will eventually get modules in ES6, although there it is :))

+8
source

http://requirejs.org/docs/start.html

The RequireJS downloadable module exists for use in a browser without using Node.js or Rhino.

To use it, download and save the script and include it in your page

 <!DOCTYPE html> <html> <head> <title>My Sample Project</title> <!-- data-main attribute tells require.js to load scripts/main.js after require.js loads. --> <script data-main="scripts/main" src="scripts/require.js"></script> </head> <body> <h1>My Sample Project</h1> </body> </html> 

The data-main attribute will point to your main script, where you can load the rest of your scripts using:

 require(["helper/util"], function(util) { //This function is called when scripts/helper/util.js is loaded. //If util.js calls define(), then this function is not fired until //util dependencies have loaded, and the util argument will hold //the module value for "helper/util". }); 

For more information, see http://requirejs.org .

+5
source

All Articles