Search code examples
javascriptnode.jsbrowserify

require is not defined error with browserify


I'm new to browserify and trying to load npm modules in browser but I'm getting the following error:

Uncaught ReferenceError: require is not defined

I'm following the tutorial from http://browserify.org/. Created javascript file with the following content:

var unique = require('uniq');

then run

npm install uniq

and

browserify main.js -o bundle.js

the bundle.js file is generated and I included it in my html but still getting the above error. Any ideas what am I doing wrong?

This is the content of final HTML file:

<!DOCTYPE html>
<html>
<head>
    <title></title>

    <script src="bundle.js"></script>
    <script src="script.js"></script>
</head>
<body>

</body>
</html>

This is the content of bundle.js: http://pastebin.com/1ECkBceB

and this is script.js:

var unique = require('uniq');


Solution

  • The "require" function is only available in the "bundle.js" script context. Browserify will take all the script files necessary and put them into the "bundle.js" file, so you should only have to include "bundle.js" in the HTML file, not the "script.js" file.