|
| 1 | +import type { RsbuildPlugin } from '@rslib/core'; |
| 2 | +import { resolve } from 'node:path'; |
| 3 | +import { fileURLToPath } from 'node:url'; |
| 4 | +import { emitDts, type EmitDtsConfig } from 'svelte2tsx'; |
| 5 | + |
| 6 | +type SvelteDtsPluginOptions = Partial<EmitDtsConfig>; |
| 7 | + |
| 8 | +const resolveProjectPath = (rootPath: string, path: string): string => resolve(rootPath, path); |
| 9 | + |
| 10 | +export function svelteDtsPlugin(options: SvelteDtsPluginOptions = {}): RsbuildPlugin { |
| 11 | + return { |
| 12 | + name: 'rslib-plugin-svelte-dts', |
| 13 | + setup(api) { |
| 14 | + api.onAfterBuild(async ({ isWatch }) => { |
| 15 | + if (!isWatch) { |
| 16 | + api.logger.start('generating declaration files...'); |
| 17 | + } |
| 18 | + |
| 19 | + const { declarationDir = './dist', libRoot = './src', tsconfig } = options; |
| 20 | + const rootPath = api.context.rootPath; |
| 21 | + const tsconfigPath = resolveProjectPath( |
| 22 | + rootPath, |
| 23 | + tsconfig ?? api.getNormalizedConfig().source.tsconfigPath ?? './tsconfig.json', |
| 24 | + ); |
| 25 | + const svelteShimsPath = options.svelteShimsPath |
| 26 | + ? resolveProjectPath(rootPath, options.svelteShimsPath) |
| 27 | + : fileURLToPath(import.meta.resolve('svelte2tsx/svelte-shims-v4.d.ts')); |
| 28 | + |
| 29 | + try { |
| 30 | + await emitDts({ |
| 31 | + declarationDir: resolveProjectPath(rootPath, declarationDir), |
| 32 | + svelteShimsPath, |
| 33 | + libRoot: resolveProjectPath(rootPath, libRoot), |
| 34 | + tsconfig: tsconfigPath, |
| 35 | + }); |
| 36 | + |
| 37 | + api.logger.ready(`declaration files generated with svelte2tsx.`); |
| 38 | + } catch (error) { |
| 39 | + api.logger.error('Failed to generate declaration files with svelte2tsx.'); |
| 40 | + api.logger.error(error); |
| 41 | + throw error; |
| 42 | + } |
| 43 | + }); |
| 44 | + }, |
| 45 | + }; |
| 46 | +} |
0 commit comments