Node-style require for in-browser javascript?

how to use require in javascript
require js cdn
browserify
add require to javascript
require js wiki
js require library
g require js
browserify standalone

Are there any libraries for in-browser javascript that provide the same flexibility/modularity/ease of use as Node's require?

To provide more detail: the reason require is so good is that it:

  1. Allows code to be dynamically loaded from other locations (which is stylistically better, in my opinion, than linking all your code in the HTML)
  2. It provides a consistent interface for building modules
  3. It is easy for modules to depend on other modules (so I could write, for instance, an API that requires jQuery so I can use jQuery.ajax()
  4. Loaded javascript is scoped, meaning I could load with var dsp = require("dsp.js"); and I would be able to access dsp.FFT, which wouldn't interfere with my local var FFT

I have yet to find a library that does this effectively. The workarounds I tend to use are:

  • coffeescript-concat -- it's easy enough to require other js, but you have to compile it, which means it is less great for fast development (e.g. building APIs in-test)

  • RequireJS -- It's popular, straightforward, and solves 1-3, but lack of scoping is a real deal-breaker (I believe head.js is similar in that it lacks scoping, though I've never had any occasion to use it. Similarly, LABjs can load and .wait() does mollify dependency issues, but it still doesn't do scoping)

As far as I can tell, there appear to be many solutions for dynamic and/or async loading of javascript, but they tend to have the same scoping issues as just loading the js from HTML. More than anything else, I would like a way to load javascript that does not pollute the global namespace at all, but still allows me to load and use libraries (just as node's require does).

EDIT (MY ANSWER): Since writing this, I have extensively used RequireJS (which now has much clearer documentation). RequireJS really was the right choice in my opinion. I'd like to clarify how the system works for people who are as confused as I was:

You can use require in everyday development. A module can be anything returned by a function (typically an object or a function) and is scoped as a parameter. You can also compile your project into a single file for deployment using r.js (in practice this is almost always faster, even though require can load scripts in parallel).

The primary difference between RequireJS and node-style require like browserify (a cool project suggested by tjameson) uses is the way modules are designed and required:

  • RequireJS uses AMD (Async Module Definition). In AMD, require takes a list of modules (javascript files) to load and a callback function. When it has loaded each of the modules, it calls the callback with each module as a parameter to the callback. Thus it's truly asynchronous and therefore well-suited to the web.
  • Node uses CommonJS. In CommonJS, require is a blocking call that loads a module and returns it as an object. This works fine for Node because files are read off the filesystem, which is fast enough, but works poorly on the web because loading files synchronously can take much longer.

In practice, many developers have used Node (and therefore CommonJS) before they ever see AMD. In addition, many libraries/modules are written for CommonJS (by adding things to an exports object) rather than for AMD (by returning the module from the define function). Therefore, lots of Node-turned-web developers want to use CommonJS libraries on the web. This is possible, since loading from a <script> tag is blocking. Solutions like browserify take CommonJS (Node) modules and wrap them up so you can include them with script tags.

Therefore, if you are developing your own multi-file project for the web, I strongly recommend RequireJS, since it is truly a module system for the web (though in fair disclosure, I find AMD much more natural than CommonJS). Recently, the distinction has become less important, since RequireJS now allows you to essentially use CommonJS syntax. Additionally, RequireJS can be used to load AMD modules in Node (though I prefer node-amd-loader).

Check out ender. It does a lot of this.

Also, browserify is pretty good. I've used require-kiss and it works. There are probably others.

I'm not sure about RequireJS. It's just not the same as node's. You may run into problems with loading from other locations, but it might work. As long as there's a provide method or something that can be called.

TL;DR- I'd recommend browserify or require-kiss.

Update:

require-kiss is now dead, and the author has removed it. I've since been using RequireJS without problems. The author of require-kiss wrote pakmanager and pakman. Full disclosure, I work with the developer.

Personally I like RequireJS better. It is much easier to debug (you can have separate files in development, and a single deployed file in production) and is built on a solid "standard".

Node-style require for in-browser javascript?, module is a function (as used in the above example). Unlike in Node.js for example, JavaScript in browsers doesn’t come with a require function to load modules dynamically. There are some implementations which try to fill this hole, but as I’ve pointed out in my previous require() post none of them really fit my needs.

I wrote a small script which allows asynchronous and synchronous loading of Javascript files, which might be of some use here. It has no dependencies and is compatible to Node.js & CommonJS. You can even bundle multiple modules in one file to reduce HTTP requests on production servers. The usage is pretty easy:

<script type="text/javascript" src="require.js"></script>
<script type="text/javascript">
    var ModuleA = require('modulea') // Sync loading of a script in the module directory
    ModuleA.funcA();

    require('./path/moduleb.js', callbackB); // Async loading of a script anywhere else
    function callbackB(ModuleB) {
        ModuleB.funcB();
    }
</script>

More details and the code can be found in my blog: http://pixelsvsbytes.com/2013/02/js-require-for-browsers-better-faster-stronger/ The code is also on GitHub: https://github.com/letorbi/tarp.require

RequireJS, RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. The `module` variable is missing. That is the only thing in the spec you are missing. However for broader compatibility with other modules written for NodeJS or RequireJS, you may want to support assigning to `module.exports`, and/or `this`, or automatically exporting the return value.

A variation of Ilya Kharlamov great answer, with some code to make it play nice with chrome developer tools.

//
///- REQUIRE FN
// equivalent to require from node.js
function require(url){
    if (url.toLowerCase().substr(-3)!=='.js') url+='.js'; // to allow loading without js suffix;
    if (!require.cache) require.cache=[]; //init cache
    var exports=require.cache[url]; //get from cache
    if (!exports) { //not cached
            try {
                exports={};
                var X=new XMLHttpRequest();
                X.open("GET", url, 0); // sync
                X.send();
                if (X.status && X.status !== 200)  throw new Error(X.statusText);
                var source = X.responseText;
                // fix (if saved form for Chrome Dev Tools)
                if (source.substr(0,10)==="(function("){ 
                    var moduleStart = source.indexOf('{');
                    var moduleEnd = source.lastIndexOf('})');
                    var CDTcomment = source.indexOf('//@ ');
                    if (CDTcomment>-1 && CDTcomment<moduleStart+6) moduleStart = source.indexOf('\n',CDTcomment);
                    source = source.slice(moduleStart+1,moduleEnd-1); 
                } 
                // fix, add comment to show source on Chrome Dev Tools
                source="//@ sourceURL="+window.location.origin+url+"\n" + source;
                //------
                var module = { id: url, uri: url, exports:exports }; //according to node.js modules 
                var anonFn = new Function("require", "exports", "module", source); //create a Fn with module code, and 3 params: require, exports & module
                anonFn(require, exports, module); // call the Fn, Execute the module
                require.cache[url]  = exports = module.exports; //cache obj exported by module
            } catch (err) {
                throw new Error("Error loading module "+url+": "+err);
            }
    }
    return exports; //require returns object exported by module
}
///- END REQUIRE FN

What is this Javascript "require"?, This guide gives you all you need to get started with JavaScript module syntax. as well as JavaScript being used in other contexts (Node.js, for example). The good news is that modern browsers have started to support module if you've already got your module code written in an object-oriented style. Once require is ready, the entire loaded source code is wrapped in a new function, which takes in require, module, exports, and all other exposed variables as arguments. This creates a new functional scope just for that module so that there is no pollution of the rest of the Node.js environment.

(function () {
    // c is cache, the rest are the constants
    var c = {},s="status",t="Text",e="exports",E="Error",r="require",m="module",S=" ",w=window;
    w[r]=function R(url) {
        url+=/.js$/i.test(url) ? "" : ".js";// to allow loading without js suffix;
        var X=new XMLHttpRequest(),module = { id: url, uri: url }; //according to the modules 1.1 standard
        if (!c[url])
            try {
                X.open("GET", url, 0); // sync
                X.send();
                if (X[s] && X[s] != 200) 
                    throw X[s+t];
                Function(r, e, m, X['response'+t])(R, c[url]={}, module); // Execute the module
                module[e] && (c[url]=module[e]);
            } catch (x) {
                throw w[E](E+" in "+r+": Can't load "+m+S+url+":"+S+x);
            }
        return c[url];
    }
})();

Better not to be used in production because of the blocking. (In node.js, require() is a blocking call is well).

Requiring modules in Node.js: Everything you need to know, Node.js & NPM (NPM comes with Node.js, you don't need to install it index.js file so that we can use the converted versions in our browser. The primary difference between RequireJS and node-style require like browserify (a cool project suggested by tjameson) uses is the way modules are designed and required: RequireJS uses AMD (Async Module Definition). In AMD, require takes a list of modules (javascript files) to load and a callback function. When it has loaded each of the modules, it calls the callback with each module as a parameter to the callback.

Webmake bundles Node-style modules to Browser, give it a try.

Using and Running Node.js Modules in The Browser, Use a node-style require() to organize your browser code and load modules installed by npm. browserify will recursively analyze all the require() calls in your app  How to Make Simple Node.js Modules Work in the Browser Posted on September 27, 2013 by Richard Rodger Node.js is all about writing small, simple modules that do one thing, and do it well.

JavaScript modules, want to use Node.js APIs (buffer, crypto, fork, events, streams, …) prefer to write CommonJS-style modules with require. Existing  The define() function accepts two optional parameters (a string that represent a module ID and an array of required modules) and one required parameter (a factory method). The return of the factory method MUST return the implementation for your module (in the same way that the Module Pattern does).

Use ES6 JavaScript syntax (require, import etc.) in your Front end , The CommonJS (CJS) format is used in Node.js and uses require and (UMD) format can be used both in the browser and in Node.js. How to enable JavaScript in your browser Nowadays almost all web pages contain JavaScript, a scripting programming language that runs on visitor's web browser. It makes web pages functional for specific purposes and if disabled for some reason, the content or the functionality of the web page can be limited or unavailable.

browserify/browserify: browser-side require() the node.js way, “Browserify lets you require('modules') in the browser by bundling up all of your which was released in 2011 and pioneered the usage of node.js style require  As far as solving the actual problem is concerned, you need to use fetch instead: fetch('my-file.txt').then(r => r.text()).then(contents => { console.log(contents); }); (this will load the file from the server, provided it is in the same folder) – Chris G Aug 15 at 9:56 |

Comments
  • Note RequireJS does actually support modularity and can scope. Since asking, I've used it a bit more extensively. In my opinion, it is functionality-packed but takes a lot of documentation reading to use effectively, and it needs some form of first-class synchronous loading before it is perfect.
  • Is the distinction of being asynchronous that meaningful? whenever i require code, i am basically blocked on being able to continue because it defines functions and such i need to do anything...
  • Cool, haven't tried browserify yet, but it looks like exactly what I need.
  • The link to require-kiss seems to be dead. Simple (re)searching didn't lead anywhere - where did it go?
  • @JoelPurra - require-kiss has been removed and been replaced by pakmanager. I recommend require-js now. I've updated the answer.
  • nice answer here man :), mind checking out the question I just did that is similar to this one (but different at the same time)? stackoverflow.com/questions/43237875/…
  • Thank you Lucio! I have been looking for a minimal solution like this for a long time. I extended it to support relative paths. See below.
  • shouldn't be "exports:{}" a property of "module"? and the call be (R, module.exports, module)
  • @LucioM.Tato I am not sure, can't see any mention of module.exports in Modules 1.1 standard. You can always call require(module.id) to get the exports
  • Yes. You're right I was thinking of node.js modules implementation. I've added some modifications to the code in your really good answer, in order to make it play nice with Chrome Dev Tools (I'm using it as Debug time IDE). I'll post the code as another answer to this question, in case is useful to somebody else.
  • Thanks Trausti. If you're using javascript, you'll should check github.com/luciotato/LiteScript (beta). PD: Which level of CC Saga are you playing now? :P