Add default to CommonJS require


Problem

If you ever needed to transform a JavaScript file from:

require('foo');

To:

require('foo').default;

This codemod does not transform existing require().default.

Solution

Then you can use require-default-codemod:

npx require-default-codemod <path>

The codemod appends the default property to CommonJS require.

To run the codemod in your current working directory:

npx require-default-codemod .

For more ways to run the codemod, see usage or options.

Methodology

This codemod was created using jscodeshift.

The implementation was pretty straightforward using the AST explorer:

  1. Find the require identifier
  2. Filter out those with default property
  3. Replace with an expression that has the original value and the default property

Code

Check out the GitHub repository for more details.



Please support this site and join our Discord!