Skip to content

Instantly share code, notes, and snippets.

@amannn
Created October 19, 2022 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amannn/171b35b62aadc8bb92eb022a3c1f7d7c to your computer and use it in GitHub Desktop.
Save amannn/171b35b62aadc8bb92eb022a3c1f7d7c to your computer and use it in GitHub Desktop.
/**
* 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