ts-morph
ts-morph copied to clipboard
find if a declaration is used by next/dynamic imports
I'm using ts-morph
to make a script that list all declarations that should be removed from a codebase (dead code).
It's considering as "dead code" many declarations that are imported using next/dynamic
imports, which look like this:
import dynamic from 'next/dynamic'
const PhoneModal = dynamic(
() => import(/* webpackChunkName: "PhoneModal" */ './PhoneModal')
)
Is there a way, from a declaration, to detect if it's used by such a dynamic import, right now I check each declaration node like this:
function isReferencedInAnotherFile(node) {
if (!Node.isReferenceFindable(node)) return false
const file = node.getSourceFile()
return !!node.findReferencesAsNodes().find((n) => {
return n.getSourceFile() !== file
})
}
So "check if this node is used in any other file than the one it's exported from". But findReferencesAsNodes()
does not consider dynamic imports as references, obviously.
I solved this by taking inspiration from this post: https://github.com/dsherret/ts-morph/issues/732