Created
June 21, 2018 06:37
-
-
Save jincod/88a4e5f843eb34a5bae2b7ad5ab97de4 to your computer and use it in GitHub Desktop.
jscodeshift codemod for material-ui
This file contains 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
gci -Include *.js,*.jsx -Recurse | % {npm run jscodeshift -- -t material-core.js $_.FullName } |
This file contains 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
export default function transformer (file, api) { | |
const j = api.jscodeshift | |
return j(file.source) | |
.find(j.ImportDeclaration) | |
.forEach(path => { | |
const pathStr = path.value.source.value | |
if (pathStr.startsWith('material-ui-icons/')) { | |
path.value.source.value = | |
path.value.source.value.replace('material-ui-icons/', '@material-ui/icons/'); | |
j(path).replaceWith( | |
j.importDeclaration(path.value.specifiers, path.value.source) | |
); | |
} | |
if (pathStr.startsWith('material-ui/') || pathStr === 'material-ui') { | |
path.value.specifiers.forEach(spec => { | |
let newPath = pathStr.replace(/^material-ui(.*(?=\/))?/, '@material-ui/core') | |
if (spec.imported) { | |
// handles non-default imports | |
// import { CardContent } from 'material-ui/Card' -> import CardContent from '@material-ui/core/CardContent' | |
// import { CardContent as asdf } from 'material-ui/Card' -> import asdf from '@material-ui/core/CardContent' | |
// import { withStyles } from 'material-ui/styles' -> import withStyles from '@material-ui/core/styles/withStyles' | |
newPath = '@material-ui/core/' + spec.imported.name | |
if (spec.imported.name === 'withStyles') { | |
newPath = '@material-ui/core/styles/withStyles' | |
} | |
path.insertBefore( | |
j.importDeclaration( | |
[j.importDefaultSpecifier(spec.local)], | |
j.literal(newPath) | |
) | |
) | |
} else { | |
// handles default imports | |
// import Card from 'material-ui/Card' -> import Card from '@material-ui/core/Card' | |
if (pathStr.includes('/colors/')) newPath = newPath.replace('/core/', '/core/colors/') | |
if (pathStr.includes('/styles/')) newPath = newPath.replace('/core/', '/core/styles/') | |
path.insertBefore( | |
j.importDeclaration([ | |
spec | |
], j.literal(newPath)) | |
) | |
} | |
}) | |
path.replace() | |
} | |
}).toSource({ quote: 'single', objectCurlySpacing: false }) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment