0
0
NodejsDebug / FixBeginner · 4 min read

How to Fix 'require is not defined' Error in Node.js

The require is not defined error happens when you try to use CommonJS require in an environment that expects ES modules. To fix it, either switch your code to use import statements or configure your project to use CommonJS modules by setting "type": "commonjs" in package.json.
🔍

Why This Happens

This error occurs because Node.js supports two module systems: CommonJS and ES modules. The require function is part of CommonJS, but if your project or file is treated as an ES module, require is not available. This often happens when package.json has "type": "module" or when using .mjs files.

javascript
const fs = require('fs');
console.log('File system module loaded');
Output
ReferenceError: require is not defined
🔧

The Fix

To fix this, you can either:

  • Use ES module syntax with import instead of require.
  • Or set your project to use CommonJS modules by removing "type": "module" from package.json or setting it to "commonjs".

This ensures require is defined and works as expected.

javascript
import fs from 'fs';
console.log('File system module loaded');
Output
File system module loaded
🛡️

Prevention

To avoid this error in the future:

  • Decide on one module system (CommonJS or ES modules) for your project and stick to it.
  • Use import and export for ES modules, and require and module.exports for CommonJS.
  • Check your package.json "type" field to match your code style.
  • Use a linter like ESLint with module rules to catch mismatches early.
⚠️

Related Errors

Other errors related to module usage include:

  • SyntaxError: Unexpected token import - Happens when using import in CommonJS files.
  • Cannot use import statement outside a module - Occurs if type is not set to module but import is used.
  • ReferenceError: exports is not defined - Happens when mixing ES modules with CommonJS export syntax.

Key Takeaways

The 'require is not defined' error means your code is treated as an ES module but uses CommonJS syntax.
Use 'import' statements for ES modules or set 'type' to 'commonjs' in package.json to use 'require'.
Keep your project consistent with one module system to avoid confusion and errors.
Lint your code to catch module syntax mismatches early.
Check file extensions and package.json settings to control module behavior.