Attempting to use require() instead of import in ES module

Loading

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 .mjs for ES modules
  • Use .cjs for 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

  1. Start by changing your package.json to "type": "module"
  2. Rename files that need to keep require() to .cjs
  3. 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 .cjs and 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

  1. Be consistent – stick to one module system per file
  2. Use named imports for better tree-shaking:
   import { useState, useEffect } from 'react';
  1. Prefer static imports unless you need dynamic imports
  2. Update older packages that only support CommonJS

Tools to Help Migration

  1. ESLint with import/no-commonjs rule
  2. TypeScript (can compile either module system)
  3. Babel (for backward compatibility)
  4. Webpack/Rollup (can handle both systems)

Leave a Reply

Your email address will not be published. Required fields are marked *