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');
To solve the "ReferenceError require is not defined" error, remove the type property if it's set to module in your package. json file and rename any files that have a . mjs extension to have a . js extension.
Browserify is an open-source JavaScript bundler tool that allows developers to write and use Node. js-style modules that compile for use in the browser.
Browserify allows us to use Node-style modules in the browser. Normally when we want to include some library code in our project, we include another script tag on the page.
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.
I personally prefer to keep my library code and application code seperate. So i also create something like a bundle.js
and a script.js
.
there is a simple workaround, that makes this work. This is somewhere in my browserify-file:
window.require = require;
this will expose require
into the "global" namespace. You can then require all you want from your script.js
.
You do give up ONE advantage, though: you'll have to include all the required libraries in your browserify file. You don't get the luxury of it finding all your dependencies, then!
I fully expect people to cry "dirty hack" or "this is not how it's meant to be". Yes, maybe. But I want those files seperate. And as long as i don't include anything else that is called "require", i'll be fine, thank you very much.
Sometimes one global can make all the difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With