Node.js中跨文件使用变量报错ReferenceError: require is not defined如何解决?
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.jsonhas a"type": "module"entry - Your files use the
.mjsextension 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:
- Open your project's
package.json(if you don't have one, runnpm init -yin PowerShell to create it) - Look for a line that says
"type": "module"— delete it if it exists - Make sure both your files use the
.jsextension (not.mjs) - One quick critical note: Your
balanceBTCis a function, so don't forget to call it inmain.js! Update that line to:console.log(balances.balanceBTC()); // Add the () to execute the function - 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:
- Add
"type": "module"to yourpackage.json(this tells Node.js to treat all.jsfiles as ES Modules) - Update
balance.jsto use ES Module exports:const balanceBTC = () => { return arrayCleaned[0]; }; export { balanceBTC }; // Or shorthand for simplicity: export const balanceBTC = () => arrayCleaned[0]; - Update
main.jsto use ES Module imports (note the required.jssuffix here):import { balanceBTC } from './balance.js'; console.log(balanceBTC()); // Don't forget to call the function! - 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

