Node.js 'require is not defined' 错误解决方法

在使用 Node.js 开发时,你可能会遇到以下错误:

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/home/blackCat/codes/test/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///home/blackCat/codes/test/app.js:2:13
    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)

Node.js v18.16.1
```</p>
<p>根据报错提示,你的代码是在一个被视为 ES 模块的环境中执行的,而在 ES 模块中不能使用 `require` 关键字。相反,你应该使用 `import` 关键字来导入模块。</p>
<h2>解决方法</h2>
<p>要解决这个问题,有两种方法:</p>
<h3>1. 将文件扩展名改为 `.cjs`</h3>
<p>将你的文件扩展名从 `.js` 改为 `.cjs`,这将使其被视为 CommonJS 模块而不是 ES 模块。例如,将 `app.js` 改为 `app.cjs`。</p>
<h3>2. 使用 `import` 关键字</h3>
<p>如果你希望继续使用 ES 模块,那么你应该使用 `import` 关键字来导入模块。你需要将你的代码改写为类似以下的形式:</p>

```javascript
import { createServer } from 'http';
import { Server } from 'socket.io';

const httpServer = createServer();
const io = new Server(httpServer);

httpServer.listen(3000, () => {
  console.log('Server is running on port 3000');
});

io.on('connection', (socket) => {
  console.log('A user connected');
  // 处理连接的逻辑
});

请注意,你需要确保你的项目中已经安装了所需的依赖项,可以使用 `npm install` 或 `yarn install` 命令来安装它们。

Node.js 'require is not defined' 错误解决方法 - ES 模块与 CommonJS 模块

原文地址: https://www.cveoy.top/t/topic/pJ6O 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录