What is require()?
Require() is the feature or function of the NodeJS,
require is defined in Node.js. Browser’s console cannot run NodeJS require function.
What is “Uncaught ReferenceError: require is not defined”?
When it occurs?
Whenever you try to run require () function outside the NodeJS, you got “Uncaught ReferenceError: require is not defined” that is a client-side error because require is not the function that is built into the browser to run your script.
Browser does not have to require () when you run it on the browser, it will show you the error “reference error: require is not defined.”
How to solve “Uncaught ReferenceError: require is not defined.”
To solve the “Uncaught ReferenceError: require is not defined,” we have three methods:
- Script tag
But before applying any method, install NodeJS into the machine.
If it is already installed, then check its version inside NodeJS command prompt or machine command prompt by using the command below:
One of the most important things you make sure that the file going to be used to run this function should have a “.js” extension
If it is still throwing an error, then you can follow the given methods:
- Include in script tag: <script>.
- Add synchronous dependencies in NodeJS like CommonJS.
- You can also add AMD (asynchronous module definition) implementation.
METHODS To Apply:
Script tag use to solve “Uncaught ReferenceError: require is not defined”
<script src = “script/require.JS” > </script>
It is a client-side practice that comprises most of them requires a build step before deployment.
Change the module type to commonJS in the package.JSON file.
“Type” : “commonJS”
Browserify: you can use most of the NodeJS modules in the browser but not all the modules.
Rollup: A new competitor holds ES6 modules and includes tree-shaking abilities (remove unused code).
AMD (asynchronous module definition):
Note: in your search for making a choice on which one to choose, Bower is only for package dependencies, and it has no opinion on module definitions like CommonJS and AMD.
In this article, we have discussed how you can fix the “ReferenceError: require is not defined” and it’s possible three solution methods that you can apply on NodeJS.
Suggested Read: 500 Internal server error