Created
October 19, 2022 15:34
-
-
Save amannn/171b35b62aadc8bb92eb022a3c1f7d7c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Converts lodash imports to use named imports. | |
* | |
* E.g.: | |
* ``` | |
* import noop from 'lodash/noop'; | |
* ``` | |
* ... to ... | |
* ``` | |
* import { noop } from 'lodash'; | |
* ``` | |
* | |
* Usage: | |
* ```sh | |
* npx jscodeshift -t lodash-es6-imports.tsx src --parser=tsx | |
* ``` | |
*/ | |
import type { API, FileInfo } from 'jscodeshift'; | |
export default function transform(file: FileInfo, api: API) { | |
const j = api.jscodeshift; | |
const root = j(file.source); | |
root.find(j.ImportDeclaration).forEach(element => { | |
const importPath = element.value.source.value?.toString(); | |
const { node } = element; | |
if (!importPath?.startsWith('lodash/')) { | |
return; | |
} | |
const fnNameImport = importPath.split('/').pop(); | |
if (!fnNameImport) { | |
throw new Error(`Could not parse import path: ${importPath}`); | |
} | |
const localImportName = node.specifiers?.[0]?.local?.name; | |
if (localImportName !== fnNameImport) { | |
throw new Error( | |
`Import name ${localImportName} does not match function name ${fnNameImport}` | |
); | |
} | |
node.specifiers = [j.importSpecifier(j.identifier(fnNameImport))]; | |
node.source = j.literal(`lodash`); | |
}); | |
return root.toSource(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment