|
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(); |
|
} |