Making codemods for javascript

What are codemods

  • codemods => code modification
  • scripts or tools that assist in making systematic changes to source code.
  • They are often used for refactoring tasks, such as renaming a variable or function across multiple files, updating API usage, or even converting code from one language or library to another.
  • Checking out other codebases codemods is a good starting point to get the gist of making one for yourself.

If i would migrate styled-components to emotion.js

ASIS:

import styled from 'styled-components';

TOBE:

import styled from '@emotion/styled';

I would need a way to find this specific import statement in the file with regex.

const packageImportRegex = /'styled-components'/;

Implementing to replace a specific substring, in this case 'styled-components'.

Implementing jscodeshift transform file


import { FileInfo } from 'jscodeshift';

export default function transformer(file: FileInfo) {
	const packageImportRegex = /'styled-components'/;
	file.source.replace(packageImportRegex, "'@emotion/styled'");
}

Using replace will only replace the first instance and is sufficient because imports should happen once in a file anyway.

💡
Replacing import statements didn't require the fancy way of selecting nodes by their AST types.

Execution

npx jscodeshift --transform path/to/codemod --extensions js,ts,jsx,tsx --parser tsx path/to/target

Reference

https://github.com/facebook/jscodeshift