![]()
The error occurs when you try to use CommonJS require() syntax in a file that’s using ES modules (typically indicated by "type": "module" in package.json or .mjs extension). Here’s how to properly handle this:
Quick Fixes
1. Convert require() to import
Before (CommonJS):
const React = require('react');
const { useState } = require('react');
After (ES Modules):
import React from 'react';
import { useState } from 'react';
2. Dynamic Imports (for conditional requires)
Before:
const module = condition ? require('./moduleA') : require('./moduleB');
After:
const module = await (condition ? import('./moduleA') : import('./moduleB'));
Configuration Solutions
1. Set Module System in package.json
For ES modules:
{
"type": "module"
}
For CommonJS (if you need to keep using require()):
{
"type": "commonjs"
}
2. File Extensions
- Use
.mjsfor ES modules - Use
.cjsfor CommonJS modules
Advanced Scenarios
1. Using Both Systems in One Project
// In an ES module file
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const legacyModule = require('./legacy-module.cjs');
2. Transitioning Large Codebases
- Start by changing your
package.jsonto"type": "module" - Rename files that need to keep
require()to.cjs - Gradually convert files to use
import
Common Errors and Fixes
1. “require is not defined”
Solution: Either:
- Convert to ES modules (
import) - Or rename file to
.cjsand use CommonJS
2. “Cannot use import outside a module”
Solution: Add "type": "module" to package.json
3. “Warning: To load an ES module…”
Solution: Ensure file extensions match module system
Best Practices
- Be consistent – stick to one module system per file
- Use named imports for better tree-shaking:
import { useState, useEffect } from 'react';
- Prefer static imports unless you need dynamic imports
- Update older packages that only support CommonJS
Tools to Help Migration
- ESLint with
import/no-commonjsrule - TypeScript (can compile either module system)
- Babel (for backward compatibility)
- Webpack/Rollup (can handle both systems)
