Last active
May 8, 2024 15:43
-
-
Save illume/e03fb61f296d18954a9bc2a12df6d7fb to your computer and use it in GitHub Desktop.
For refactoring mui imports
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
// For refactoring named imports from top level to individual component imports. | |
// | |
// -import { Box, Button } from '@mui/material'; | |
// +import Box from '@mui/material/Box'; | |
// +import Button from '@mui/material/Button'; | |
// | |
// Why? Because CRA development server runs faster this way. | |
// | |
// Has some bugs but works mostly. | |
// You probably need to modify a few imports manually, and test everything. | |
// | |
// npm install -g jscodeshift | |
// jscodeshift -t refactor-imports.js --extensions=tsx --parser=tsx src/ | |
// npm run format | |
// npm run lint -- --fix | |
module.exports = function (fileInfo, api) { | |
const j = api.jscodeshift; | |
const root = j(fileInfo.source, { parser: require('recast/parsers/typescript') }); | |
root | |
.find(j.ImportDeclaration) | |
.filter(path => path.node.source.value === '@mui/material') | |
.forEach(path => { | |
const newImports = []; | |
path.node.specifiers.forEach(specifier => { | |
const importedName = specifier.imported.name; | |
let newImportPath; | |
if (importedName === 'useTheme' || importedName === 'Theme') { | |
newImportPath = `@mui/material`; | |
newImports.push( | |
j.importDeclaration( | |
[j.importSpecifier(j.identifier(importedName))], | |
j.literal(newImportPath) | |
) | |
); | |
} else if (importedName.endsWith('Props')) { | |
const baseComponentName = importedName.replace('Props', ''); | |
newImportPath = `@mui/material/${baseComponentName}`; | |
newImports.push( | |
j.importDeclaration( | |
[j.importSpecifier(j.identifier(importedName))], | |
j.literal(newImportPath) | |
) | |
); | |
} else { | |
newImportPath = `@mui/material/${importedName}`; | |
newImports.push( | |
j.importDeclaration( | |
[j.importDefaultSpecifier(j.identifier(importedName))], | |
j.literal(newImportPath) | |
) | |
); | |
} | |
}); | |
newImports.forEach(newImport => { | |
j(path).insertAfter(newImport); | |
}); | |
j(path).remove(); | |
}); | |
return root.toSource(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment