Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

prepack.js

94 lines2.2 KB

1import fs from 'node:fs'
2import path from 'node:path'
3​
4// Currently unused as life-cycle scripts do not run on CI
5​
6console.log('Running prepack script')
7​
8/**
9 * Files to copy to the dist directory
10 * @type {string[]}
11 */
12const FILES_TO_COPY = ['README.md']
13​
14/**
15 * Fields to remove from the package.json copy
16 * @type {string[]}
17 */
18const FIELDS_TO_REMOVE = [
19 'devDependencies',
20 'files',
21 'publishConfig',
22 'scripts',
24​
25/**
26 * Replaces 'dist/' or './dist/' prefix from a file path with './'
27 * @param {string} filePath - The file path to process
28 * @returns {string} The path without dist prefix
29 */
30function removeDist(filePath) {
31 return filePath.replace(/^(\.\/)?dist\//, './')
33​
34/**
35 * Recursively processes exports object to remove dist prefixes
36 * @param {Record<string, any>} exports - The exports object to process
37 * @returns {Record<string, any>} The processed exports object
38 */
39function processExports(exports) {
40 return Object.fromEntries(
41 Object.entries(exports).map(([key, value]) => [
42 key,
43 typeof value === 'string'
44 ? removeDist(value)
45 : typeof value === 'object' && value !== null
46 ? processExports(value)
47 : value,
48 ]),
49 )
51​
52console.log('Copying modified package.json')
53​
54/** @type {Record<string, any>} */
55const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'))
56​
57const distPackageJson = { ...packageJson }
58​
59if (distPackageJson.types) {
60 distPackageJson.types = removeDist(distPackageJson.types)
62​
63if (distPackageJson.module) {
64 distPackageJson.module = removeDist(distPackageJson.module)
66​
67if (distPackageJson.exports) {
68 distPackageJson.exports = processExports(distPackageJson.exports)
70​
71for (const field of FIELDS_TO_REMOVE) {
72 delete distPackageJson[field]
74​
75if (!fs.existsSync('dist')) {
76 fs.mkdirSync('dist', { recursive: true })
78​
79fs.writeFileSync(
80 path.join('dist', 'package.json'),
81 JSON.stringify(distPackageJson, null, 2),
83​
84console.log('Copying other files')
85for (const fileName of FILES_TO_COPY) {
86 if (fs.existsSync(fileName)) {
87 fs.copyFileSync(fileName, path.join('dist', fileName))
88 console.log(`${fileName}`)
89 } else {
90 console.log(`${fileName} not found, skipping`)
91 }
93​
94console.log('prepack complete')