You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行本地Node.js服务时遇require未定义错误求助

Fixing "require is not defined" in Node.js (index.js & server.js)

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 your package.json to revert to CommonJS mode (where require() 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';
      

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 with import and ensure your HTML includes the script with type="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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:32:14