Helpers for writing codemods
npm install @monteway/codeshiftInternal jscodeshift helpers used in @monteway/app for easier codemod implementation.
``bash`
npm i -D @monteway/codeshift
Adds new import inside imports group. You can specify where the import should go, by selecting an existing import inside source file and set if the new one should go before of after it.
1. Let's have index.tsx file with following content:
`js
import ReactDOM from 'react-dom';
// some more content that is irrelevant
`
2. Now write a codemod file codeshift.mjs that will be run using jscodeshift. \react-dom
In this example we want to add a React default import before import.
`js
import { appendImports } from '@monteway/codeshift';
export default function codemod(file, api, options) {
const jscodeshift = api.jscodeshift;
let source = jscodeshift(file.source);
source = appendImports(
jscodeshift,
source,
'BEFORE_FIRST',
/^react-dom$/,
import React from 'react';,
);
return source.toSource();
}
`
3. The output of running codeshift.mjs for index.tsx content would be:
`diff
+ import React from 'react';
import ReactDOM from 'react-dom';
// some more content that is irrelevant
`
Finds a default export and wraps it with a call experssion.
1. Let's have a index.tsx file with the following content:
`ts
import React from 'react';
function Component() {
return <>Hello, world!>;
}
export default Component;
`
2. Now write a codemod file codeshift.mjs that will be run using jscodeshift. \Component
In this example we want to wrap the with memo.
`js
import { wrapDefaultExport } from '@monteway/codeshift';
export default function codemod(file, api, options) {
const jscodeshift = api.jscodeshift;
let source = jscodeshift(file.source);
source = wrapDefaultExport(jscodeshift, source, 'memo');
return source.toSource();
}
`
3. The output of running codeshift.mjs for index.tsx content would be:
`diff
import React from 'react';
function Component() {
return <>Hello, world!>;
}
- export default Component;
+ export default memo(Component);
`
> Notice that for this code to run we would need to add import for memo. We could solve it by usingReact.memo
> instead of memo, since React is already imported, but right now,wrapDefaultExport
> the does not accept anything other than identifier node,React.memo`, since this a member experssion, not an identifier.
> so we could not use