Skip to content

Instantly share code, notes, and snippets.

@souporserious
Created April 4, 2023 15:19
Show Gist options
  • Save souporserious/8dd0f7e9ba29652cec503208a03c6977 to your computer and use it in GitHub Desktop.
Save souporserious/8dd0f7e9ba29652cec503208a03c6977 to your computer and use it in GitHub Desktop.
Utility function to grab type declarations from an NPM package
import fs from 'node:fs/promises'
import path from 'node:path'
/** Fetches the types for a locally installed NPM package. */
export async function getTypeDeclarations(packageName) {
const [parentPackage, submodule] = packageName.split('/')
const parentPackagePath = path.resolve(
process.cwd(),
'node_modules',
parentPackage,
'package.json'
)
try {
const packageJson = JSON.parse(
await fs.readFile(parentPackagePath, 'utf-8')
)
let typesPath
if (submodule) {
if (packageJson.typesVersions) {
const typeVersionsField = packageJson.typesVersions['*']
if (typeVersionsField) {
const typesPathFromTypeVersions = typeVersionsField[submodule]
if (typesPathFromTypeVersions) {
typesPath = path.resolve(
process.cwd(),
'node_modules',
parentPackage,
typesPathFromTypeVersions[0] // TODO: handle multiple types paths
)
}
}
}
} else {
const typesField = packageJson.types || packageJson.typings
if (typesField) {
typesPath = path.resolve(
process.cwd(),
'node_modules',
parentPackage,
typesField
)
}
}
if (!typesPath) {
typesPath = path.resolve(
process.cwd(),
'node_modules',
`@types/${packageName}`,
'index.d.ts'
)
}
try {
return fs.readFile(typesPath, 'utf-8')
} catch (error) {
console.error(`Could not find types for: ${packageName}`, error)
}
} catch (error) {
console.error(`Could not find package.json for: ${packageName}`, error)
}
return ''
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment