|
| 1 | +import { createRequire } from 'node:module'; |
| 2 | +import { resolve } from 'node:path'; |
| 3 | +import type { RsbuildPlugin } from '@rslib/core'; |
| 4 | +import { emitDts } from 'svelte2tsx'; |
| 5 | + |
| 6 | +const require = createRequire(import.meta.url); |
| 7 | + |
| 8 | +export interface SvelteDtsPluginOptions { |
| 9 | + declarationDir?: string; |
| 10 | + libRoot?: string; |
| 11 | + tsconfig?: string; |
| 12 | + svelteShimsPath?: string; |
| 13 | +} |
| 14 | + |
| 15 | +const resolveProjectPath = (rootPath: string, path: string): string => resolve(rootPath, path); |
| 16 | + |
| 17 | +export function svelteDtsPlugin(options: SvelteDtsPluginOptions = {}): RsbuildPlugin { |
| 18 | + return { |
| 19 | + name: 'rslib-plugin-svelte-dts', |
| 20 | + setup(api) { |
| 21 | + api.onAfterBuild(async () => { |
| 22 | + const { |
| 23 | + declarationDir = './dist', |
| 24 | + libRoot = './src', |
| 25 | + tsconfig = 'tsconfig.json', |
| 26 | + } = options; |
| 27 | + |
| 28 | + const rootPath = api.context.rootPath; |
| 29 | + const svelteShimsPath = options.svelteShimsPath |
| 30 | + ? resolveProjectPath(rootPath, options.svelteShimsPath) |
| 31 | + : require.resolve('svelte2tsx/svelte-shims-v4.d.ts'); |
| 32 | + |
| 33 | + try { |
| 34 | + await emitDts({ |
| 35 | + declarationDir: resolveProjectPath(rootPath, declarationDir), |
| 36 | + svelteShimsPath, |
| 37 | + libRoot: resolveProjectPath(rootPath, libRoot), |
| 38 | + tsconfig: resolveProjectPath(rootPath, tsconfig), |
| 39 | + }); |
| 40 | + |
| 41 | + console.log('Svelte DTS generation complete'); |
| 42 | + } catch (error) { |
| 43 | + console.error('Svelte DTS generation failed:', error); |
| 44 | + throw error; |
| 45 | + } |
| 46 | + }); |
| 47 | + }, |
| 48 | + }; |
| 49 | +} |
0 commit comments