-
Notifications
You must be signed in to change notification settings - Fork 0
/
get-ts-declarations.ts
50 lines (39 loc) · 1.39 KB
/
get-ts-declarations.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import fs from "node:fs";
import path from "node:path";
import { safeJSONParse } from "pastable";
import { rollup } from "rollup";
import dts from "rollup-plugin-dts";
import type { PackageJson } from "type-fest";
const getDeps = (pkg: PackageJson) =>
Object.keys(pkg.dependencies ?? {}).concat(
Object.keys(pkg.peerDependencies ?? {})
);
const getPkg = async (name: string) =>
safeJSONParse<PackageJson>(
await fs.promises.readFile(`./node_modules/${name}/package.json`, "utf8")
);
const getTypesDeclaration = async (name: string) => {
const pkg = await getPkg(name);
if (!pkg.types && !pkg.typings) return;
const types = (pkg.types ?? pkg.typings)!;
const bundle = await rollup({
input: path.resolve("./node_modules/", name, types),
plugins: [dts({ respectExternal: true })],
external: (id) => getDeps(pkg).includes(id),
});
const result = await bundle.generate({});
return result.output[0].code;
};
const getTsDeclarations = async () => {
const reactDeclaration = await getTypesDeclaration("@types/react");
fs.writeFileSync("./react.d.ts", reactDeclaration!);
return {
name: "@types/react",
code: `declare module '@types/react' { ${reactDeclaration} }`,
};
};
// eslint-disable-next-line import/no-unused-modules
// export default getTsDeclarations;
// uncomment to run with bun
await getTsDeclarations();
// console.log(await getTsDeclarations());