rsnext/packages/next/build/babel/plugins/dangerously-remove-unused-imports.ts
2019-12-06 11:46:00 -05:00

36 lines
1.1 KiB
TypeScript

import { NodePath, PluginObj } from '@babel/core'
import * as BabelTypes from '@babel/types'
export default function(): PluginObj<any> {
return {
name: 'dangerously-remove-unused-imports',
visitor: {
Program: {
exit(path: NodePath<BabelTypes.Program>) {
Object.entries(path.scope.bindings).forEach(([k, v]) => {
if (v.referenced || v.kind !== 'module') return
if (
!(
v.path.type === 'ImportDefaultSpecifier' ||
v.path.type === 'ImportSpecifier' ||
v.path.type === 'ImportNamespaceSpecifier'
) ||
!(v.path.parent.type === 'ImportDeclaration')
) {
throw new Error(
`invariant: unknown import binding: ${v.path.type} / parent: ${v.path.parent.type}`
)
}
if (v.path.parent.specifiers.length === 1) {
v.path.parentPath.remove()
} else {
v.path.remove()
}
})
},
},
},
}
}