Skip to content

Instantly share code, notes, and snippets.

@fersilva16
Last active December 23, 2021 03:23
Show Gist options
  • Save fersilva16/bd379ea3d6c744fd907d85bdac3f34e1 to your computer and use it in GitHub Desktop.
Save fersilva16/bd379ea3d6c744fd907d85bdac3f34e1 to your computer and use it in GitHub Desktop.
Transform imports from a file that has been moved to a new shared workspace
import type { API, FileInfo } from 'jscodeshift';
import path from 'path';
/**
* Path to the original file, if you're using imports without extensions,
* then don't provide the extension to the path
* example:
* import File from '../file.tsx'; // Use `path/to/original/file.tsx`
* import File from '../file'; // Use just `path/to/original/file`
*/
const filePath = path.resolve('path/to/original/file');
// The shared workspace name
const workspace = '@new/workspace';
export default function transform(fileInfo: FileInfo, { jscodeshift }: API) {
const root = jscodeshift(fileInfo.source);
const dirpath = path.dirname(fileInfo.path);
const basename = path.basename(filePath);
const imports: string[] = [];
root
.find(jscodeshift.ImportDeclaration, (node) => {
if (
node.source.type !== 'Literal' &&
node.source.type !== 'StringLiteral'
) {
return false;
}
if (typeof node.source.value !== 'string') return false;
return filePath === path.resolve(dirpath, node.source.value);
})
.replaceWith(({ node }) => {
node.specifiers.forEach((specifier) => {
if (specifier.type === 'ImportSpecifier') {
imports.push(specifier.imported.name);
}
});
return jscodeshift.importDeclaration(
[jscodeshift.importSpecifier(jscodeshift.identifier(basename))],
jscodeshift.stringLiteral(workspace),
node.importKind,
);
});
imports.forEach((name) => {
root
.find(jscodeshift.Identifier, { name })
.replaceWith(({ node, parent }) => {
if (parent.value.type === 'MemberExpression') return node;
return jscodeshift.memberExpression(
jscodeshift.identifier(basename),
jscodeshift.identifier(node.name),
);
});
});
return root.toSource();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment