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

Node.js中跨文件使用变量报错ReferenceError: require is not defined如何解决?

Fixing "ReferenceError: require is not defined" in Node.js v14.10.1

Hey there! Let's break down why you're hitting this error and how to fix it. The require is not defined issue almost always happens because Node.js is treating your files as ES Modules instead of the older CommonJS format that uses require/exports.

Why this happens

Node.js v14 supports both module formats, but it switches to ES Modules if:

  • Your package.json has a "type": "module" entry
  • Your files use the .mjs extension instead of .js

Since your code is written for CommonJS (using require and exports), the ES Module environment doesn't recognize those functions.


Solution 1: Stick with CommonJS (keep your existing code structure)

This is the quickest fix if you don't want to switch module systems:

  1. Open your project's package.json (if you don't have one, run npm init -y in PowerShell to create it)
  2. Look for a line that says "type": "module" — delete it if it exists
  3. Make sure both your files use the .js extension (not .mjs)
  4. One quick critical note: Your balanceBTC is a function, so don't forget to call it in main.js! Update that line to:
    console.log(balances.balanceBTC()); // Add the () to execute the function
    
  5. Run your code in PowerShell like normal: node main.js

Solution 2: Switch to ES Modules (use import/export)

If you want to use the modern ES Module syntax instead:

  1. Add "type": "module" to your package.json (this tells Node.js to treat all .js files as ES Modules)
  2. Update balance.js to use ES Module exports:
    const balanceBTC = () => { return arrayCleaned[0]; };
    export { balanceBTC };
    // Or shorthand for simplicity: export const balanceBTC = () => arrayCleaned[0];
    
  3. Update main.js to use ES Module imports (note the required .js suffix here):
    import { balanceBTC } from './balance.js';
    console.log(balanceBTC()); // Don't forget to call the function!
    
  4. Run the code the same way: node main.js

Either approach should resolve the require is not defined error. Just pick the module system that fits your project needs!

内容的提问来源于stack exchange,提问作者Lawnmoers The Epic Gamer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:31:27