require is not defined? Node.js
Solution 1:
This can now also happen in Node.js as of version 14.
It happens when you declare your package type as module in your package.json
. If you do this, certain CommonJS variables can't be used, including require
.
To fix this, remove "type": "module"
from your package.json
and make sure you don't have any files ending with .mjs
.
Solution 2:
In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you're running the Chrome browser), the rest of the execution environment such as libraries available are not the same.
node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require()
is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require()
.
require()
is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require()
.
There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require()
that work similarly (though not identically).
But, you won't be running a web server in your browser as that is not something the browser has the capability to do.
You may be interested in browserify which lets you use node-style modules in a browser using require()
statements.