update-exports.ts64 lines · main
| 1 | import * as fs from 'node:fs' |
| 2 | import * as path from 'node:path' |
| 3 | |
| 4 | const SRC_DIR = path.resolve(__dirname, '..', 'src') |
| 5 | |
| 6 | interface ExportMap { |
| 7 | [key: string]: { |
| 8 | import: string |
| 9 | types: string |
| 10 | } |
| 11 | } |
| 12 | |
| 13 | function getAllSourceFiles(dir: string): ExportMap { |
| 14 | const entries = fs.readdirSync(dir, { withFileTypes: true }) |
| 15 | const exportsMap: ExportMap = {} |
| 16 | |
| 17 | for (const entry of entries) { |
| 18 | const fullPath = path.join(dir, entry.name) |
| 19 | |
| 20 | if (entry.isDirectory()) { |
| 21 | Object.assign(exportsMap, getAllSourceFiles(fullPath)) |
| 22 | } else if (entry.isFile() && /\.(ts|tsx|css)$/.test(entry.name)) { |
| 23 | const relativePath = path.relative(SRC_DIR, fullPath) |
| 24 | const noExtension = relativePath.replace(/\.(ts|tsx)$/, '') |
| 25 | const segments = noExtension.split(path.sep) |
| 26 | |
| 27 | // If filename is "index", remove it from the export path |
| 28 | const isIndex = segments[segments.length - 1] === 'index' |
| 29 | const exportSegments = isIndex ? segments.slice(0, -1) : segments |
| 30 | |
| 31 | const subpath = `./${exportSegments.join('/')}` // clean export |
| 32 | const filePath = `./src/${relativePath.replace(/\\/g, '/')}` |
| 33 | |
| 34 | exportsMap[subpath] = { |
| 35 | import: filePath, |
| 36 | types: filePath, |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | return exportsMap |
| 42 | } |
| 43 | |
| 44 | function updatePackageJson(exportsMap: ExportMap): void { |
| 45 | const packageJsonPath = path.resolve(__dirname, '..', 'package.json') |
| 46 | const packageJsonRaw = fs.readFileSync(packageJsonPath, 'utf8') |
| 47 | const packageJson = JSON.parse(packageJsonRaw) |
| 48 | |
| 49 | packageJson.exports = { |
| 50 | './package.json': './package.json', |
| 51 | '.': { |
| 52 | import: './index.tsx', |
| 53 | types: './index.tsx', |
| 54 | }, |
| 55 | ...exportsMap, |
| 56 | } |
| 57 | |
| 58 | fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2)) |
| 59 | console.log('✅ package.json exports updated (with clean index paths).') |
| 60 | } |
| 61 | |
| 62 | // Run the export generation |
| 63 | const exportsMap = getAllSourceFiles(SRC_DIR) |
| 64 | updatePackageJson(exportsMap) |