I am tyring to get node.js working and when I call a ‘require’, I get the following error Uncaught ReferenceError: require is not defined
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Enter your email to get $200 in credit for your first 60 days with DigitalOcean.
New accounts only. By submitting your email you agree to our Privacy Policy.
Hi there,
This error usually occurs when trying to use Node.js’s
require()
function in a context where it isn’t defined. This is common when you try to userequire()
in client-side JavaScript, which runs in a web browser.Web browsers don’t support the
require()
function natively because it is part of Node.js’s module system (CommonJS), not part of standard JavaScript. To use modules in client-side JavaScript, you would generally use the ES6import
statement. However, this assumes that the script you’re importing is an ES6 module, and it must be served from a web server due to CORS (Cross-Origin Resource Sharing) policies in browsers.If you’re trying to use a Node.js library in client-side code, you will often need to use a tool like Browserify or Webpack. These tools bundle your code and its dependencies into a single JavaScript file that can be included in your HTML.
If you are indeed trying to use Node.js and the error persists, it could be due to several reasons:
The script is not running in a Node.js environment. Make sure you’re running your script with Node.js, e.g.
node your_script.js
in the command line.The module you’re trying to require is not installed. If you’re trying to require a third-party module, make sure it’s installed using
npm install module_name
.The path to the module is incorrect. If you’re trying to require a local file, make sure the path to the file is correct. For example, if you’re in the same directory as the file, the require statement would be
require('./filename')
.If none of these solutions work, feel free to share more details about your exact setup!
Best,
Bobby