Open History to see the last commit
1import { link, mkdir } from 'fs/promises'
2import { dirname, relative } from 'path'
3import fg from 'fast-glob'
4β
5const constants = {
6 DIST_TYPES_DIRECTORY: 'dist/types',
7 OUTPUT_DIRECTORY: '.',
8 DIST_TYPE_FILES_GLOB: 'dist/types/**/*.d.ts',
9}
10β
11/*
12`prepack` lifecycle script which links type declaration files from the dist folder to the package root.
13allows using types in package exports as such:
14β
15`"types": "./index.d.ts"`
16β
17and subpath exports
18β
19```json
20 "./some-subpath": {
21 "types": "./some-subpath/index.d.ts", // β
works with `"modeResolution": "node"`
22 "default": "./build/some-subpath/index.mjs"
23 },
24```
25β
26When TypeScript is configured with `moduleResolution: node`, type declaration file directory structures are expected
27to exactly match the subpath export as in the example above.
28β
29```json
30 "./some-subpath": {
31 "types": "./build/dist/some-subpath/index.d.ts", // β does not work with `"moduleResolution": "node"`
32 "default": "./build/some-subpath/index.mjs"
33 },
34```
35β
36It's important to support `"moduleResolution": "node"` as many Angular applications are still configured this way.
37β
38In the `postpack` lifecycle script these links are removed to keep a clean development environment
39 */
40async function prepack() {
41 console.log('Running prepack script to prepare types for publishing')
42β
43 const typeFiles = await fg([constants.DIST_TYPE_FILES_GLOB])
44 if (typeFiles.length === 0) return
45β
46 const destDirs = [
47 ...new Set(
48 typeFiles
49 .map((file) => {
50 const dest = relative(constants.DIST_TYPES_DIRECTORY, file)
51 return dirname(dest)
52 })
53 .filter((dir) => dir !== constants.OUTPUT_DIRECTORY),
54 ),
55 ]
56β
57 await Promise.all(destDirs.map((dir) => mkdir(dir, { recursive: true })))
58 await Promise.all(
59 typeFiles.map((file) => {
60 const dest = relative(constants.DIST_TYPES_DIRECTORY, file)
61 return link(file, dest)
62 }),
63 )
64β
65 console.log(`Linked ${typeFiles.length} type files`)
66}
67β
68prepack().catch(console.error)