Skip to content

Instantly share code, notes, and snippets.

@zthxxx
Last active January 2, 2024 08:54
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 zthxxx/234d9849309273970282ced5459374ef to your computer and use it in GitHub Desktop.
Save zthxxx/234d9849309273970282ced5459374ef to your computer and use it in GitHub Desktop.
auto merge duplicate import, support distinguish between import and import type, but not support with namespace import or duplicate default import
import {
namedTypes as types,
} from 'ast-types'
import type {
Options as RecastOptions,
} from 'recast'
import type {
Transform,
FileInfo,
API,
Collection,
ASTPath,
} from 'jscodeshift'
/**
* usage:
* $ npx jscodeshift --extensions=js,jsx,ts,tsx --ignore-config=.gitignore -t scripts/maintain/codeshift-duplicate-import.ts <source-dir>
* $ TIMING=1 npx eslint --quiet --format codeframe --fix --ext=js,jsx,ts,tsx $(git ls-files -m)
*
* auto merge duplicate import, support distinguish between import and import type
* but not support with namespace import or duplicate default import
*
* examples:
* import { Table } from 'react'
* import { FC } from 'react'
* to
* import{ Table, FC } from 'react'
* -----
* import { Table } from 'react'
* import tp from 'react'
* to
* import tp, { Table } from 'react'
* -----
* import tp, { Table } from 'react'
* import tpx { FC } from 'react'
* to
* import tp, { Table, FC } from 'react'
* import tpx from 'react'
* (cannot merge duplicate default-import)
* -----
* import { Table } from 'react'
* import * as tpx from 'react'
* to
* (do nothing, because import namespace)
* -----
* import { Table } from 'react'
* import type { FC } from 'react'
* to
* (do nothing, distinguish between import and import type)
*/
const ignoreSourcePaths: RegExp[] = [
/node_modules/,
/\.umi/,
]
export const transform: Transform = (fileInfo: FileInfo, api: API) => {
if (ignoreSourcePaths.some(ignorePath => ignorePath.test(fileInfo.path))) {
return
}
const { jscodeshift: j } = api
const root = j(fileInfo.source)
/**
* ast example see:
* https://astexplorer.net/#/gist/010d21058c33bb9ffaf83cc095f95a81/45e851a77d9818b40fecad967e9671de780377b7
*/
const importCollection: Collection<types.ImportDeclaration> = root.find(types.ImportDeclaration)
if (!importCollection.length) {
return
}
const importMap: {
[importPath: string]: ASTPath<types.ImportDeclaration>;
} = {}
const importTypeMap: {
[importPath: string]: ASTPath<types.ImportDeclaration>;
} = {}
let hasDuplicate = false
importCollection.forEach(path => {
const { node } = path
const { specifiers, importKind, source } = node
if (!specifiers) return
const hasNamespace = hasNamespaceImport(node)
if (hasNamespace) return
const map = importKind === 'type' ? importTypeMap : importMap
const importPath = source.value as string
// first import of path
if (!map[importPath]) {
map[importPath] = path
return
}
hasDuplicate = true
const { node: firstImport } = map[importPath]
const importDefault: types.ImportDefaultSpecifier | undefined = specifiers
.filter(specifier => types.ImportDefaultSpecifier.check(specifier))
?.[0] as types.ImportDefaultSpecifier
const existedNamed: Set<string> = new Set(firstImport.specifiers!
.filter(specifier => types.ImportSpecifier.check(specifier))
.map((specifier: types.ImportSpecifier) => specifier.local.name),
)
const namedImports = specifiers
.filter(specifier => types.ImportSpecifier.check(specifier))
/**
* ensure named import to distinct,
* but sometime need manual disable `checkRedeclarationInScope` in class `ScopeHandler` in node_modules/@babel/parser/lib/index.js
*/
.filter((specifier: types.ImportSpecifier) => !existedNamed.has(specifier.local.name))
// merge named imports to first-import-declaration
firstImport.specifiers!.push(...namedImports)
// has duplicate default-import, only keep default-import but drop named-import
if (hasDefaultImport(firstImport) && importDefault) {
node.specifiers = [importDefault]
return
}
if (importDefault) {
firstImport.specifiers!.unshift(importDefault)
}
path.prune()
})
if (!hasDuplicate) return
return root.toSource(recastStyleOption)
}
const recastStyleOption: RecastOptions = {
tabWidth: 2,
useTabs: false,
wrapColumn: 80,
quote: 'single',
trailingComma: true,
}
const hasNamespaceImport = (importNode: types.ImportDeclaration): boolean => Boolean(
importNode
.specifiers
?.some(specifier => types.ImportNamespaceSpecifier.check(specifier)),
)
const hasDefaultImport = (importNode: types.ImportDeclaration): boolean => Boolean(
importNode
.specifiers
?.some(specifier => types.ImportDefaultSpecifier.check(specifier)),
)
export const parser = 'tsx'
// default function will used in jscodeshift
export default transform
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment