镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Commit b585797

Browse files
chrisbbreuerclaude
andcommitted
fix(vite-plugin): keep declarations through Vite's outDir emptying
By default the plugin generated in buildStart, and Vite then emptied outDir in its renderStart hook, so a build ended with no .d.ts files. Build-mode generation now runs in renderStart, after outDir is prepared, once per build even when Vite runs one pass per output format. The default source root is now the folder of build.lib.entry, else src, instead of the whole project, so src/index.ts emits dist/index.d.ts and the Vite config is never declared. Adds real vite build regression tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 2b11e19 commit b585797

4 files changed

Lines changed: 182 additions & 11 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,4 @@ benchmark/oxc-emit
2727
*.node
2828
/packages/dtsx/.test-cli
2929
pantry
30+
/packages/vite-plugin/test/.vite-project-*/

‎packages/vite-plugin/README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ export default defineConfig({
3131
| Option | Type | Default | Description |
3232
|--------|------|---------|-------------|
3333
| `trigger` | `'build' \| 'serve' \| 'both'` | `'build'` | When to generate declarations |
34+
| `timing` | `'before' \| 'after'` | `'before'` | Generate before Vite writes the bundle (after it empties `outDir`) or after the build |
35+
| `root` | `string` | folder of `build.lib.entry`, else `./src` | Source root; declarations mirror the source from here |
36+
| `outdir` | `string` | Vite `build.outDir` | Output directory for declarations |
3437
| `entryPointsOnly` | `boolean` | `true` | Only generate for entry points |
3538
| `declarationDir` | `string` | Vite outDir | Output directory for declarations |
3639
| `bundle` | `boolean` | `false` | Bundle all declarations into one file |

‎packages/vite-plugin/src/index.ts‎

Lines changed: 60 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { DtsGenerationOption, GenerationStats } from '@stacksjs/dtsx'
22
import type { Plugin, ResolvedConfig, ViteDevServer } from 'vite'
33
import { watch as fsWatch } from 'node:fs'
4-
import { basename, join, resolve } from 'node:path'
4+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
55
import { generate } from '@stacksjs/dtsx'
66

77
/**
@@ -35,7 +35,9 @@ export interface DtsPluginOptions extends DtsGenerationOption {
3535
watchPatterns?: string[]
3636

3737
/**
38-
* Generate declarations before or after the build
38+
* Generate declarations before or after the build. In a build, 'before'
39+
* generates once Vite has prepared (emptied) its outDir and before it
40+
* writes the bundle, so the declarations are kept.
3941
* @default 'before'
4042
*/
4143
timing?: 'before' | 'after'
@@ -151,6 +153,9 @@ export function dts(options: DtsPluginOptions = {}): Plugin {
151153
changedFiles: new Set(),
152154
}
153155

156+
// Whether this build has generated, so multi-output builds generate once.
157+
let generatedThisBuild = false
158+
154159
/**
155160
* Generate declarations with error handling
156161
*/
@@ -274,24 +279,32 @@ export function dts(options: DtsPluginOptions = {}): Plugin {
274279
const shouldWatch = enableWatch ?? true
275280

276281
if (shouldWatch && (trigger === 'serve' || trigger === 'both')) {
277-
const root = dtsOptions.root || state.viteConfig?.root || './src'
278-
startWatcher(resolve(state.viteConfig?.root || process.cwd(), root))
282+
const { cwd, root } = normalizeConfig(dtsOptions, state.viteConfig)
283+
startWatcher(resolve(cwd!, root!))
279284
}
280285
},
281286

282287
async buildStart() {
283-
if (timing !== 'before') return
288+
if (timing !== 'before' || state.viteConfig?.command !== 'serve') return
289+
if (trigger !== 'serve' && trigger !== 'both') return
284290

285-
const shouldRun = trigger === 'both'
286-
|| (trigger === 'build' && state.viteConfig?.command === 'build')
287-
|| (trigger === 'serve' && state.viteConfig?.command === 'serve')
291+
await generateDeclarations()
292+
},
288293

289-
if (!shouldRun) return
294+
// Vite empties outDir in a `renderStart` hook ordered 'pre', after
295+
// `buildStart`. Declarations written before then would be deleted.
296+
async renderStart() {
297+
if (timing !== 'before' || generatedThisBuild) return
298+
if (state.viteConfig?.command !== 'build' || trigger === 'serve') return
290299

300+
generatedThisBuild = true
291301
await generateDeclarations()
292302
},
293303

294304
async closeBundle() {
305+
// Vite calls buildStart and renderStart once per output format, and
306+
// closeBundle once per build.
307+
generatedThisBuild = false
295308
if (timing !== 'after') return
296309

297310
if (trigger === 'build' || trigger === 'both') {
@@ -348,20 +361,56 @@ export function dts(options: DtsPluginOptions = {}): Plugin {
348361
* @returns Normalized configuration
349362
*/
350363
function normalizeConfig(options: DtsGenerationOption, viteConfig: ResolvedConfig | null): DtsGenerationOption {
351-
const root = options.root || viteConfig?.root || './src'
364+
const cwd = options.cwd || viteConfig?.root || process.cwd()
365+
const root = options.root || defaultRoot(cwd, viteConfig)
352366
const outdir = options.outdir || viteConfig?.build?.outDir || './dist'
353367

368+
// The Vite config is build tooling, not library source.
369+
const exclude = [...(options.exclude ?? [])]
370+
const configFile = viteConfig?.configFile
371+
if (!options.root && configFile && isInside(configFile, resolve(cwd, root)))
372+
exclude.push(configFile)
373+
354374
return {
355375
...options,
356-
cwd: options.cwd || viteConfig?.root || process.cwd(),
376+
cwd,
357377
root,
358378
entrypoints: options.entrypoints || ['**/*.ts'],
379+
exclude,
359380
outdir,
360381
clean: options.clean,
361382
tsconfigPath: options.tsconfigPath,
362383
}
363384
}
364385

386+
/**
387+
* The source root when none is configured: the folder holding the library
388+
* entries (`build.lib.entry`), else `src`. Declarations then mirror the
389+
* source from there, so `src/index.ts` emits `<outDir>/index.d.ts`.
390+
*/
391+
function defaultRoot(cwd: string, viteConfig: ResolvedConfig | null): string {
392+
const lib = viteConfig?.build?.lib
393+
const entry = lib ? lib.entry : undefined
394+
const entries = typeof entry === 'string' ? [entry] : Array.isArray(entry) ? entry : entry ? Object.values(entry) : []
395+
if (entries.length === 0)
396+
return './src'
397+
398+
const directories = entries.map(file => dirname(resolve(cwd, file)))
399+
return directories.reduce(commonDirectory)
400+
}
401+
402+
function commonDirectory(a: string, b: string): string {
403+
let common = a
404+
while (!isInside(b, common) && dirname(common) !== common)
405+
common = dirname(common)
406+
return common
407+
}
408+
409+
function isInside(path: string, directory: string): boolean {
410+
const rel = relative(directory, path)
411+
return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel))
412+
}
413+
365414
/**
366415
* Check if a file should be processed
367416
*/
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import { afterEach, describe, expect, test } from 'bun:test'
2+
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
3+
import { dirname, join } from 'node:path'
4+
import { build } from 'vite'
5+
6+
const pluginEntry = join(import.meta.dir, '..', 'src', 'index.ts')
7+
const projects: string[] = []
8+
9+
/** A throwaway Vite project. It sits in this package so `@stacksjs/dtsx` resolves. */
10+
function project(files: Record<string, string>): string {
11+
const dir = mkdtempSync(join(import.meta.dir, '.vite-project-'))
12+
projects.push(dir)
13+
for (const [file, text] of Object.entries(files)) {
14+
mkdirSync(dirname(join(dir, file)), { recursive: true })
15+
writeFileSync(join(dir, file), text)
16+
}
17+
return dir
18+
}
19+
20+
/** Runs `vite build` in the project, loading its `vite.config.ts`. */
21+
async function viteBuild(dir: string): Promise<void> {
22+
await build({ root: dir, configFile: join(dir, 'vite.config.ts'), logLevel: 'silent' })
23+
}
24+
25+
function config(body: string): string {
26+
return `import { dts } from ${JSON.stringify(pluginEntry)}\nexport default ${body}\n`
27+
}
28+
29+
function declarations(dir: string): string[] {
30+
return (readdirSync(dir, { recursive: true }) as string[]).filter(file => file.endsWith('.d.ts')).sort()
31+
}
32+
33+
const library = {
34+
'src/index.ts': `export { double } from './utils'\nexport const version = '1.0.0'\n`,
35+
'src/utils.ts': `export function double(value: number): number { return value * 2 }\n`,
36+
}
37+
38+
afterEach(() => {
39+
for (const dir of projects.splice(0))
40+
rmSync(dir, { recursive: true, force: true })
41+
})
42+
43+
describe('vite build with @dtsx/vite-plugin', () => {
44+
test('a library build keeps declarations next to the bundle', async () => {
45+
const dir = project({
46+
...library,
47+
'vite.config.ts': config(`{ plugins: [dts()], build: { lib: { entry: 'src/index.ts', formats: ['es'], fileName: 'index' } } }`),
48+
})
49+
await viteBuild(dir)
50+
51+
const dist = join(dir, 'dist')
52+
expect(existsSync(join(dist, 'index.js'))).toBe(true)
53+
expect(declarations(dist)).toEqual(['index.d.ts', 'utils.d.ts'])
54+
expect(readFileSync(join(dist, 'index.d.ts'), 'utf8')).toContain(`export declare const version: '1.0.0';`)
55+
expect(readFileSync(join(dist, 'utils.d.ts'), 'utf8')).toContain('export declare function double(value: number): number;')
56+
})
57+
58+
test('declarations from an earlier build are replaced, not kept by luck', async () => {
59+
const dir = project({
60+
...library,
61+
'dist/stale.d.ts': 'export declare const stale: 1;\n',
62+
'vite.config.ts': config(`{ plugins: [dts()], build: { lib: { entry: 'src/index.ts', formats: ['es'], fileName: 'index' } } }`),
63+
})
64+
await viteBuild(dir)
65+
expect(declarations(join(dir, 'dist'))).toEqual(['index.d.ts', 'utils.d.ts'])
66+
})
67+
68+
test('a library entry at the project root does not declare the Vite config', async () => {
69+
const dir = project({
70+
'index.ts': `export const answer = 42\n`,
71+
'vite.config.ts': config(`{ plugins: [dts()], build: { lib: { entry: 'index.ts', formats: ['es'], fileName: 'index' } } }`),
72+
})
73+
await viteBuild(dir)
74+
expect(declarations(join(dir, 'dist'))).toEqual(['index.d.ts'])
75+
})
76+
77+
test('without a library entry the source root is src', async () => {
78+
const dir = project({
79+
...library,
80+
'scripts/release.ts': `export const tool = true\n`,
81+
'vite.config.ts': config(`{ plugins: [dts()], build: { rolldownOptions: { input: 'src/index.ts' } } }`),
82+
})
83+
await viteBuild(dir)
84+
expect(declarations(join(dir, 'dist'))).toEqual(['index.d.ts', 'utils.d.ts'])
85+
})
86+
87+
test('several output formats generate once', async () => {
88+
const dir = project({
89+
...library,
90+
'vite.config.ts': [
91+
`import { dts } from ${JSON.stringify(pluginEntry)}`,
92+
`export default { plugins: [dts({ onSuccess: () => { (globalThis as any).__dtsxRuns += 1 } })], build: { lib: { entry: 'src/index.ts', formats: ['es', 'cjs'], fileName: 'index' } } }`,
93+
].join('\n'),
94+
})
95+
;(globalThis as any).__dtsxRuns = 0
96+
await viteBuild(dir)
97+
expect((globalThis as any).__dtsxRuns).toBe(1)
98+
expect(declarations(join(dir, 'dist'))).toEqual(['index.d.ts', 'utils.d.ts'])
99+
})
100+
101+
test('timing after generates once the bundle is written', async () => {
102+
const dir = project({
103+
...library,
104+
'vite.config.ts': config(`{ plugins: [dts({ timing: 'after' })], build: { lib: { entry: 'src/index.ts', formats: ['es'], fileName: 'index' } } }`),
105+
})
106+
await viteBuild(dir)
107+
expect(declarations(join(dir, 'dist'))).toEqual(['index.d.ts', 'utils.d.ts'])
108+
})
109+
110+
test('an explicit root and outdir are used as given', async () => {
111+
const dir = project({
112+
...library,
113+
'vite.config.ts': config(`{ plugins: [dts({ root: '.', entrypoints: ['src/**/*.ts'], outdir: 'types' })], build: { lib: { entry: 'src/index.ts', formats: ['es'], fileName: 'index' } } }`),
114+
})
115+
await viteBuild(dir)
116+
expect(declarations(join(dir, 'types'))).toEqual(['src/index.d.ts', 'src/utils.d.ts'])
117+
})
118+
})

0 commit comments

Comments
 (0)