Skip to main content
This recipe transforms the usage of the deprecated createRequireFromPath function to use the modern createRequire function from the node:module module.

What It Does

The codemod transforms:
  • createRequireFromPath import/require → createRequire
  • createRequireFromPath(path) calls → createRequire(path)
  • Variable names from requireFromPathrequire (where appropriate)

Usage

npx codemod nodejs/create-require-from-path

Example

Before
const { createRequireFromPath } = require('node:module');

// Using createRequireFromPath
const requireFromPath = createRequireFromPath('/path/to/module');
const myModule = requireFromPath('./myModule.cjs');
After
const { createRequire } = require('node:module');

// Using createRequire with a specific path
const require = createRequire('/path/to/module');
const myModule = require('./myModule.cjs');

Why Migrate?

createRequireFromPath was deprecated in favor of createRequire, which:
  • Has a clearer, more concise name
  • Provides the same functionality with a better API
  • Aligns with Node.js module system conventions
  • Is the recommended approach going forward
The createRequire function is commonly used in ES modules to load CommonJS modules or to use require.resolve() for path resolution.

Common Use Cases

Loading CommonJS from ESM

import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';

const require = createRequire(import.meta.url);
const packageJson = require('./package.json');

Resolving Module Paths

import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const modulePath = require.resolve('some-module');

Deprecation Reference

This migration addresses DEP0130.
createRequireFromPath was deprecated in Node.js v12.2.0 and may be removed in future versions. Migrate your code to avoid potential breaking changes.

Build docs developers (and LLMs) love