|
| 1 | +import * as fsPromises from 'node:fs/promises' |
1 | 2 | import { defineConfig } from 'tsdown' |
2 | 3 |
|
3 | 4 | export default defineConfig({ |
4 | 5 | entry: ['src/*.ts'], |
5 | 6 | format: ['esm', 'cjs'], |
6 | 7 | external: ['vue', '@iconify/json/package.json'], |
7 | | - exports: true, |
| 8 | + exports: { |
| 9 | + async customExports(exp) { |
| 10 | + // replace this for await with `import { glob } from 'node:fs/promises' |
| 11 | + // requires node v22.14.0+ => https://nodejs.org/api/fs.html |
| 12 | + for await (const [key, types] of getDtsTypesFiles()) { |
| 13 | + if (!exp[key]) { |
| 14 | + exp[key] = { types } |
| 15 | + } |
| 16 | + } |
| 17 | + return exp |
| 18 | + }, |
| 19 | + }, |
| 20 | + hooks: { |
| 21 | + 'build:done': async () => { |
| 22 | + await patchNode16CJSDefaultExports([ |
| 23 | + 'index', |
| 24 | + 'resolver', |
| 25 | + ]) |
| 26 | + }, |
| 27 | + }, |
8 | 28 | }) |
| 29 | + |
| 30 | +async function patchNode16CJSDefaultExports( |
| 31 | + files: string[], |
| 32 | +) { |
| 33 | + await Promise.all(files.map(async (file) => { |
| 34 | + const path = `./dist/${file}.d.cts` |
| 35 | + const content = await fsPromises.readFile(path, { encoding: 'utf8' }) |
| 36 | + const fixedContent = content.match(/export\s+\{(.*)\};/) |
| 37 | + if (fixedContent && fixedContent.length > 0) { |
| 38 | + const exports = fixedContent[1].split(',').map(e => e.trim()).filter(e => e.includes(' as default')) |
| 39 | + if (exports.length === 1) { |
| 40 | + await fsPromises.writeFile( |
| 41 | + path, |
| 42 | + content.replace(fixedContent[0], `export = ${exports[0].replace(' as default', '').trim()};`), |
| 43 | + { encoding: 'utf8' }, |
| 44 | + ) |
| 45 | + } |
| 46 | + } |
| 47 | + })) |
| 48 | +} |
| 49 | + |
| 50 | +async function* getDtsTypesFiles(): AsyncGenerator<[ |
| 51 | + key: string, |
| 52 | + types: string, |
| 53 | +], undefined, void> { |
| 54 | + const files = await fsPromises.readdir('./types/') |
| 55 | + for (const file of files) { |
| 56 | + if (file.endsWith('.d.ts') && file !== 'index.d.ts') { |
| 57 | + yield [`./types/${file.replace(/\.d\.ts$/, '')}`, `./types/${file}`] as const |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments