update-exports.ts 1.9 KB

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