MightyMouse MightyMouse - 5 months ago 1000
Javascript Question

Client on node: Uncaught ReferenceError: require is not defined

So, I am writing an application with the node/express + jade combo.

I have

client.js
, which is loaded on the client. In that file I have code that calls functions from other JavaScript files. My attempt was to use

var m = require('./messages');


in order to load the contents of
messages.js
(just like I do on the server side) and later on call functions from that file. However,
require
is not defined on the client side, and it throws an error of the form
Uncaught ReferenceError: require is not defined
.

These other JS files are also loaded on runtime at the client because I place the links at the header of the webpage. So the client knows all the functions that are exported from these other files.

How do I call these functions from these other JS files (such as
messages.js
) in the main
client.js
file that opens the socket to the server?

Answer

This is because require() does not exist in the browser/client-side JavaScript.

Now you're going to have to make some choices about your client-side JavaScript script management.

You have three options:

  1. Use <script> tag.
  2. Use a CommmonJS implementation. Synchronous dependencies like Node.js
  3. Use an AMD implementation.

CommonJS client side-implementations include:

(most of them require a build step before you deploy)

  1. Browserify - You can use most Node.js modules in the browser. This my personal favorite.
  2. Component - Focuses on simplicity. Browser only. Made by the same guy who made Express.js (most) popular Node.js web framework.
  3. Webpack - Does everything (bundles JS, CSS, etc). Made popular by the surge of React.js. Notorious for its difficult learning curve.
  4. Rollup - New contender. Leverages ES6 modules. Includes tree-shaking abilities (removes unused code).

You can read more about my comparison of Browserify vs Component.

AMD implementations include:

  1. RequireJS - Very popular amongst client-side JavaScript developers. Not my taste because of its asynchronous nature.

Note, in your search for choosing which one to go with, you'll read about Bower. Bower is only for package dependencies and is unopinionated on module definitions like CommonJS and AMD.

Hope this helps some.

Edit (2016-01-16):

Added webpack and rollup. I think it's safe to say that in 2016, it's best to avoid component. I'll eventually remove it from the list.

Comments