|
| 1 | +import type { Plugin, ResolvedConfig } from 'vite'; |
| 2 | + |
| 3 | +import path from 'node:path'; |
| 4 | +import { styleText } from 'node:util'; |
| 5 | + |
| 6 | +import ts from 'typescript'; |
| 7 | + |
| 8 | +export default function sexyDeclareType(): Plugin { |
| 9 | + let config: ResolvedConfig; |
| 10 | + let entryFiles: string[] = []; |
| 11 | + |
| 12 | + return { |
| 13 | + name: 'vite-plugin-sexy-declare-type', |
| 14 | + |
| 15 | + configResolved(resolvedConfig) { |
| 16 | + config = resolvedConfig; |
| 17 | + const libConfig = config.build.lib; |
| 18 | + |
| 19 | + if (!libConfig) { |
| 20 | + console.warn( |
| 21 | + '[sexy-declare-type] Only works with Vite library mode. Skipping.', |
| 22 | + ); |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + const entry = typeof libConfig === 'object' ? libConfig.entry : undefined; |
| 27 | + |
| 28 | + if (!entry) { |
| 29 | + console.warn( |
| 30 | + '[sexy-declare-type] No entry found in library config. Skipping.', |
| 31 | + ); |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + if (typeof entry === 'string') { |
| 36 | + entryFiles = [path.resolve(config.root, entry)]; |
| 37 | + } else if (Array.isArray(entry)) { |
| 38 | + entryFiles = entry.map((e) => path.resolve(config.root, e)); |
| 39 | + } else { |
| 40 | + entryFiles = Object.values(entry).map((e) => |
| 41 | + path.resolve(config.root, e), |
| 42 | + ); |
| 43 | + } |
| 44 | + }, |
| 45 | + |
| 46 | + closeBundle: async () => { |
| 47 | + if (entryFiles.length === 0) return; |
| 48 | + |
| 49 | + const startTime = performance.now(); |
| 50 | + |
| 51 | + const compilerOptions: ts.CompilerOptions = { |
| 52 | + declaration: true, |
| 53 | + emitDeclarationOnly: true, |
| 54 | + skipLibCheck: true, |
| 55 | + target: ts.ScriptTarget.ESNext, |
| 56 | + module: ts.ModuleKind.ESNext, |
| 57 | + moduleResolution: ts.ModuleResolutionKind.Bundler, |
| 58 | + outDir: path.resolve(config.root, config.build.outDir), |
| 59 | + esModuleInterop: true, |
| 60 | + jsx: ts.JsxEmit.Preserve, |
| 61 | + }; |
| 62 | + |
| 63 | + const host = ts.createCompilerHost(compilerOptions); |
| 64 | + const program = ts.createProgram(entryFiles, compilerOptions, host); |
| 65 | + program.emit(undefined, undefined, undefined, true); |
| 66 | + |
| 67 | + const duration = ((performance.now() - startTime) / 1000).toFixed(2); |
| 68 | + const filesCount = program |
| 69 | + .getSourceFiles() |
| 70 | + .filter((f) => !f.fileName.includes('node_modules')).length; |
| 71 | + |
| 72 | + console.log( |
| 73 | + `${styleText('green', '✓')} Sexy declarations ready in ${styleText('dim', `${duration}s`)} ${styleText('green', `(${filesCount} files)`)}`, |
| 74 | + ); |
| 75 | + }, |
| 76 | + }; |
| 77 | +} |
0 commit comments