4

I've encountered several JavaScript projects and libraries that use this require() function, in order to include other files, like this:

require('somefile')

I never heard of that, and apparently it's something of node.js, which I don't have and don't use.

I just intend to use these JavaScript libraries in my own websites, but I'm seeing all sorts of instructions involving "npm" (whatever that may be). Then there is supposedly a replacement for that called required.js, but that seems to use a different syntax, like forcing to use require([...]) or something whereas the projects I need to include just do require(...).

What is the easiest way to deal with this require(...) stuff when using JavaScript projects in regular html5 websites? (i.e. all supposed to run client side)


Addition: I already tried require.js, but it doesn't seem to work. For example, the first line in somelibrary.js is this:

var assert = require('assert')

when I previously included require.js, and then somelibrary.js, I'm getting this error:

Uncaught exception: Error: Module name "assert" has not been loaded yet for context: _. Use require([])

And this happens with anything that contains require()


Another addition: I noticed people mentioning 'browserify'. And some of the js projects I'm trying to include also recommend this. Apparently this is supposed to generate one single ready to use .js file that I can Include. But

  1. Why don't they just publish this browserified .js directly? Is there a reason why I need to compile it myself? it's supposed to be something universal for all browsers or websites, right?

  2. This browserify thing, which is apparently to avoid node.js, actually seems to require node.js itself (the instructions all mention "npm -g install browserify" etc)

5
  • 3
    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. -- requirejs.org Commented Aug 21, 2014 at 9:35
  • I tried require.js but doesn't seem to solve my problem, see edit above Commented Aug 21, 2014 at 9:55
  • Do these libraries have a package.json file? Commented Aug 21, 2014 at 9:58
  • Yes, I typically do see these 'package.json' files. Commented Aug 21, 2014 at 10:23
  • Ok, this means that these libraries follow the CommonJS module syntax and can be required from your code. But you need to use browserify, which is an additional build step. You should take a look at the description on the browserify homepage. It is really easy to start with and you can use most of the libraries from npm. Commented Aug 21, 2014 at 14:27

4 Answers 4

1

Libraries should ideally support the following, depending on its environment. Lets say you are using a library called "MyLib.js".

No module loader detected

window.MyLib

Requirejs detected

define(['MyLib'], function (MyLib) {
  // Do something
  return {};
});

CommonJS detected, like node or use of browserify or bower

var MyLib = require('MyLib');

Not all libs conform to this, but they should. Maybe the lib you were looking at only supports Node. Looking at the source of jQuery you see something like this:

if ( typeof module === "object" && typeof module.exports === "object" ) {
    // For CommonJS and CommonJS-like environments where a proper window is present,
    // execute the factory and get jQuery
    // For environments that do not inherently posses a window with a document
    // (such as Node.js), expose a jQuery-making factory as module.exports
    // This accentuates the need for the creation of a real window
    // e.g. var jQuery = require("jquery")(window);
    // See ticket #14549 for more info
    module.exports = global.document ?
        factory( global, true ) :
        function( w ) {
            if ( !w.document ) {
                throw new Error( "jQuery requires a window with a document" );
            }
            return factory( w );
        };
} else {
    factory( global );
}
Sign up to request clarification or add additional context in comments.

3 Comments

Sounds reasonable. Unfortunately, I've run into quite some very useful libraries that don't do this :(
Or you should use a module library when developing applications ;-)
Ehm, sorry, I have no idea what that means :) In this case I am simply building some websites where I don't want to reinvent the wheel and just use several existing JavaScript libraries.
1

Node.js is now used a lot to manage JavaScript projects, even if the project is client side. For example, Grunt, Bower, Browserify, Gulp and plenty other build tools run on Node.js, even though you can use them on client-side projects. Using those tools doesn't make your project depend on Node in production. Node is only used for development. To install those tools, one uses npm, which is a package manager. Like Maven or Ivy, npm will install packages and their dependencies by downloading them from the internet.

Libraries which install instructions involve npm are meant to be used in Node, but may be used in the browser after they have been converted with Browserify. Download the library with npm, then convert it to browser style using Browserify (which you install using npm, because itself runs on Node). You should get a single JavaScript file that you can import in your client-side project.

Libraries that are especially targeted for the browser will often refer to Bower as the install method instead of npm. Bower is also a package manager, but it is designed to download and install library written for browsers, not Node. If a library you want is available on Bower, you are able to download it and all its dependencies with bower install <lib>. Bower will put all files in a bower_components folder in the current directory. You can then copy those files to your project, or make your project import them directly from this folder.

Comments

1

So, browserify is simply a tool which makes it possible to use node-style modules in the browser. Yes, you do need to have node.js installed in order to use npm and browserify. But these times you need node.js for the most of your frontend toolsets.

npm is full of modules that are written in JavaScript and also run in the browser. With browserify you can use these modules in the browser.

It works by shimming the whole require mechanism and making it work in the browser. This also means that you can organize your code in modules:

// add.js
module.exports = function(x, y) {
    return x + y;
}

// app.js
var add = require('./add.js');
var result = add(7, 8);

Now you could generate your bundle (the only script you need to include in your html) by just running browserify app.js -o bundle.js.

If you don't like the browserify approach you can also use the --standalone option to generate a JavaScript file in the UMD format. You could then simply include this in your html and use it with window.add for the previous example.

Comments

0

The require statement is handled by require.js, which can be used standalone in a javascript environment. It is a module loader which optimises loading dependencies in the browser. There is a Node.js implementation for it, but that doesn't mean that you have to use Node, you can just include require in your project.

(p.s: npm is Node Package Manager, and would be unnecessary for your project unless you're using Node. It streamlines the inclusion of javascript node modules into your project.)

5 Comments

I tried require.js but doesn't seem to solve my problem, see edit above
So you're hitting the syntax problem you described above (require([...])). Have you inherited this code, or are you trying to adapt examples to use non-Node style syntax? The require(...) syntax IS require.js, just the Node flavour. If you want to use this module loading stuff, you would have to use their syntax.
Not really. Require.js is an AMD module loader. require(...) is also specified by a CommonJS specification which is being used by node.js and also Browserify which makes these modules usable on the browser side.
OK, but basically in order to do that you'd have to use either node or browserify. Op seems to just want a mechanism for managing libraries on the client side rather than hooking into an engine
@Fishbowl, no I haven't done anything yet, I'm even just trying to include the library, but it already fails there. See also my addition about Browserify above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.