Last active
May 11, 2022 07:05
-
-
Save jukben/17da2376a677cf430e4403a951a29314 to your computer and use it in GitHub Desktop.
no-duplicate-imports codemod (https://github.com/facebook/jscodeshift)
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
/** | |
* Copyright (c) 2019-present, ProductBoard, Inc. | |
* All rights reserved. | |
*/ | |
export default function transform(file, api) { | |
const j = api.jscodeshift; | |
const imports = j(file.source) | |
.find(j.ImportDeclaration) | |
.nodes(); | |
const newImports = imports.reduce((acc, v, i, arr) => { | |
const source = v.source.value; | |
if (acc[source]) { | |
acc[source].push(v); | |
return acc; | |
} | |
acc[source] = [v]; | |
return acc; | |
}, {}); | |
const omit = []; | |
return j(file.source) | |
.find(j.ImportDeclaration) | |
.filter(i => newImports[i.node.source.value].length > 1) | |
.replaceWith(p => { | |
const source = p.node.source.value; | |
if (p.node.specifiers[0].type === 'ImportNamespaceSpecifier') { | |
return p.node; | |
} | |
const imports = newImports[source].reduce((acc, v, i, arr) => { | |
return [ | |
...acc, | |
...v.specifiers.filter(i => i.type !== 'ImportNamespaceSpecifier'), | |
]; | |
}, []); | |
p.node.specifiers = imports; | |
if (omit[source]) { | |
return ''; | |
} | |
omit[source] = true; | |
return p.node; | |
}) | |
.toSource(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment