运行本地Node.js服务时遇require未定义错误求助
Hey there! Let’s troubleshoot that frustrating require is not defined error you’re seeing with your index.js and server.js files. This is one of the most common Node.js gotchas, so let’s walk through the most likely causes and fixes below:
1. You’re running the file in a browser (not Node.js)
The require() function is only available in Node.js environments—browsers don’t support it natively. If you’re opening index.js or server.js directly in a browser, that’s definitely the issue.
- Fix: Run your files using the Node.js CLI instead. Open your terminal, navigate to your project folder, and run:
node server.js # or node index.js
2. Your project is set to use ES Modules instead of CommonJS
If your package.json includes a "type": "module" line, Node.js switches to ES Module mode by default. In this mode, require() isn’t supported—you have to use import/export instead.
- Fixes:
- Option 1: Remove the
"type": "module"line from yourpackage.jsonto revert to CommonJS mode (whererequire()works normally). - Option 2: Replace all
require()calls with ES Module syntax. For example:// Old CommonJS syntax const express = require('express'); const server = require('./server.js'); // New ES Module syntax import express from 'express'; import server from './server.js';
- Option 1: Remove the
3. You’re mixing environments (frontend code using Node.js syntax)
If index.js is a frontend script meant to run in the browser but you’re using require() inside it, browsers won’t recognize the function.
- Fix: Use a bundler like Webpack or Rollup to package your frontend code. These tools can resolve
require()calls and convert them into browser-compatible code. Alternatively, switch to using ES Modules withimportand ensure your HTML includes the script withtype="module":<script type="module" src="index.js"></script>
Double-check which of these scenarios applies to your setup—chances are it’s one of the first two. Let me know if you need more details on any of these fixes!
内容的提问来源于stack exchange,提问作者John Mauricio

