diff --git a/.changeset/declaration-import-extensions.md b/.changeset/declaration-import-extensions.md new file mode 100644 index 00000000..d1f2742c --- /dev/null +++ b/.changeset/declaration-import-extensions.md @@ -0,0 +1,5 @@ +--- +'@tanstack/vite-config': patch +--- + +Fix relative specifiers in emitted declarations that did not resolve. A module whose name contains a dot, such as `./HeadContent.dev` for `HeadContent.dev.tsx`, now gets `.js` (or `.cjs`). A directory import, such as `../hmr` for `hmr/index.ts`, now becomes `../hmr/index.js` instead of `../hmr.js`. In the CJS declarations, a specifier written as `./foo.js` for a TypeScript source `foo.ts` now becomes `./foo.cjs`, matching `foo.d.cts`. Each case is decided from the source files next to the importing module; anything not found there is handled as before. diff --git a/integrations/internal-declarations/package.json b/integrations/internal-declarations/package.json index a2aff100..31f10e71 100644 --- a/integrations/internal-declarations/package.json +++ b/integrations/internal-declarations/package.json @@ -51,6 +51,7 @@ }, "devDependencies": { "@tanstack/vite-config": "workspace:*", + "typescript": "catalog:", "vite": "catalog:", "vitest": "catalog:" } diff --git a/integrations/internal-declarations/snap/cjs/Head.dev.d.cts b/integrations/internal-declarations/snap/cjs/Head.dev.d.cts new file mode 100644 index 00000000..1a7759e2 --- /dev/null +++ b/integrations/internal-declarations/snap/cjs/Head.dev.d.cts @@ -0,0 +1 @@ +export declare const headMode: "dev"; diff --git a/integrations/internal-declarations/snap/cjs/extended.d.cts b/integrations/internal-declarations/snap/cjs/extended.d.cts new file mode 100644 index 00000000..8c6b5d95 --- /dev/null +++ b/integrations/internal-declarations/snap/cjs/extended.d.cts @@ -0,0 +1,3 @@ +export { headMode } from './Head.dev.cjs'; +export { joinPaths } from './nested/paths.cjs'; +export type LazyPaths = typeof import('./nested/paths.cjs'); diff --git a/integrations/internal-declarations/snap/cjs/hmr/index.d.cts b/integrations/internal-declarations/snap/cjs/hmr/index.d.cts new file mode 100644 index 00000000..b73a7d5c --- /dev/null +++ b/integrations/internal-declarations/snap/cjs/hmr/index.d.cts @@ -0,0 +1 @@ +export type HmrStyle = 'full' | 'partial'; diff --git a/integrations/internal-declarations/snap/cjs/specifiers.d.cts b/integrations/internal-declarations/snap/cjs/specifiers.d.cts new file mode 100644 index 00000000..308cbb59 --- /dev/null +++ b/integrations/internal-declarations/snap/cjs/specifiers.d.cts @@ -0,0 +1,4 @@ +export { headMode } from './Head.dev.cjs'; +export type { HmrStyle } from './hmr/index.cjs'; +export type LazyHead = typeof import('./Head.dev.cjs'); +export type LazyHmrStyle = import('./hmr/index.cjs').HmrStyle; diff --git a/integrations/internal-declarations/snap/esm/Head.dev.d.ts b/integrations/internal-declarations/snap/esm/Head.dev.d.ts new file mode 100644 index 00000000..1a7759e2 --- /dev/null +++ b/integrations/internal-declarations/snap/esm/Head.dev.d.ts @@ -0,0 +1 @@ +export declare const headMode: "dev"; diff --git a/integrations/internal-declarations/snap/esm/extended.d.ts b/integrations/internal-declarations/snap/esm/extended.d.ts new file mode 100644 index 00000000..c06e9a9e --- /dev/null +++ b/integrations/internal-declarations/snap/esm/extended.d.ts @@ -0,0 +1,3 @@ +export { headMode } from './Head.dev.js'; +export { joinPaths } from './nested/paths.js'; +export type LazyPaths = typeof import('./nested/paths.js'); diff --git a/integrations/internal-declarations/snap/esm/hmr/index.d.ts b/integrations/internal-declarations/snap/esm/hmr/index.d.ts new file mode 100644 index 00000000..b73a7d5c --- /dev/null +++ b/integrations/internal-declarations/snap/esm/hmr/index.d.ts @@ -0,0 +1 @@ +export type HmrStyle = 'full' | 'partial'; diff --git a/integrations/internal-declarations/snap/esm/specifiers.d.ts b/integrations/internal-declarations/snap/esm/specifiers.d.ts new file mode 100644 index 00000000..6baa0c9d --- /dev/null +++ b/integrations/internal-declarations/snap/esm/specifiers.d.ts @@ -0,0 +1,4 @@ +export { headMode } from './Head.dev.js'; +export type { HmrStyle } from './hmr/index.js'; +export type LazyHead = typeof import('./Head.dev.js'); +export type LazyHmrStyle = import('./hmr/index.js').HmrStyle; diff --git a/integrations/internal-declarations/snap/internal/Head.dev.d.ts b/integrations/internal-declarations/snap/internal/Head.dev.d.ts new file mode 100644 index 00000000..1a7759e2 --- /dev/null +++ b/integrations/internal-declarations/snap/internal/Head.dev.d.ts @@ -0,0 +1 @@ +export declare const headMode: "dev"; diff --git a/integrations/internal-declarations/snap/internal/extended.d.ts b/integrations/internal-declarations/snap/internal/extended.d.ts new file mode 100644 index 00000000..c06e9a9e --- /dev/null +++ b/integrations/internal-declarations/snap/internal/extended.d.ts @@ -0,0 +1,3 @@ +export { headMode } from './Head.dev.js'; +export { joinPaths } from './nested/paths.js'; +export type LazyPaths = typeof import('./nested/paths.js'); diff --git a/integrations/internal-declarations/snap/internal/hmr/index.d.ts b/integrations/internal-declarations/snap/internal/hmr/index.d.ts new file mode 100644 index 00000000..b73a7d5c --- /dev/null +++ b/integrations/internal-declarations/snap/internal/hmr/index.d.ts @@ -0,0 +1 @@ +export type HmrStyle = 'full' | 'partial'; diff --git a/integrations/internal-declarations/snap/internal/specifiers.d.ts b/integrations/internal-declarations/snap/internal/specifiers.d.ts new file mode 100644 index 00000000..6baa0c9d --- /dev/null +++ b/integrations/internal-declarations/snap/internal/specifiers.d.ts @@ -0,0 +1,4 @@ +export { headMode } from './Head.dev.js'; +export type { HmrStyle } from './hmr/index.js'; +export type LazyHead = typeof import('./Head.dev.js'); +export type LazyHmrStyle = import('./hmr/index.js').HmrStyle; diff --git a/integrations/internal-declarations/src/Head.dev.ts b/integrations/internal-declarations/src/Head.dev.ts new file mode 100644 index 00000000..8d636622 --- /dev/null +++ b/integrations/internal-declarations/src/Head.dev.ts @@ -0,0 +1,2 @@ +// A module whose base name contains a dot. +export const headMode = 'dev' as const diff --git a/integrations/internal-declarations/src/extended.ts b/integrations/internal-declarations/src/extended.ts new file mode 100644 index 00000000..0fbe9445 --- /dev/null +++ b/integrations/internal-declarations/src/extended.ts @@ -0,0 +1,5 @@ +// Relative specifiers that already carry an extension stay as written. +export { headMode } from './Head.dev.js' +export { joinPaths } from './nested/paths.js' + +export type LazyPaths = typeof import('./nested/paths.js') diff --git a/integrations/internal-declarations/src/hmr/index.ts b/integrations/internal-declarations/src/hmr/index.ts new file mode 100644 index 00000000..6fd512ed --- /dev/null +++ b/integrations/internal-declarations/src/hmr/index.ts @@ -0,0 +1,2 @@ +// Imported through its directory, `./hmr`. +export type HmrStyle = 'full' | 'partial' diff --git a/integrations/internal-declarations/src/specifiers.ts b/integrations/internal-declarations/src/specifiers.ts new file mode 100644 index 00000000..6aa2fe23 --- /dev/null +++ b/integrations/internal-declarations/src/specifiers.ts @@ -0,0 +1,7 @@ +// Relative specifiers without an extension: a module whose base name +// contains a dot, and a directory with an index module. +export { headMode } from './Head.dev' +export type { HmrStyle } from './hmr' + +export type LazyHead = typeof import('./Head.dev') +export type LazyHmrStyle = import('./hmr').HmrStyle diff --git a/integrations/internal-declarations/tests/build.test.ts b/integrations/internal-declarations/tests/build.test.ts index 5a8129af..2dc9ddf7 100644 --- a/integrations/internal-declarations/tests/build.test.ts +++ b/integrations/internal-declarations/tests/build.test.ts @@ -3,6 +3,7 @@ import { tmpdir } from 'node:os' import { dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { tanstackViteConfig } from '@tanstack/vite-config' +import ts from 'typescript' import { build, mergeConfig } from 'vite' import { afterAll, describe, expect, it } from 'vitest' import type { Options } from '@tanstack/vite-config' @@ -62,10 +63,14 @@ describe('check internal declarations build output', () => { it('should keep @internal members only in the internal declarations', () => { const internal = readDeclarations(`${distDir}/internal`) expect(Object.keys(internal)).toEqual([ + 'Head.dev.d.ts', + 'extended.d.ts', 'extra.d.ts', + 'hmr/index.d.ts', 'index.d.ts', 'nested/paths.d.ts', 'self.d.ts', + 'specifiers.d.ts', ]) expect(internal['index.d.ts']).toContain('_pending: Map;') expect(internal['index.d.ts']).toContain('_strictParams') @@ -94,6 +99,57 @@ describe('check internal declarations build output', () => { } }) + it('should add extensions to dotted and directory specifiers', () => { + for (const dir of ['esm', 'cjs', 'internal']) { + const extension = dir === 'cjs' ? 'cjs' : 'js' + const file = dir === 'cjs' ? 'specifiers.d.cts' : 'specifiers.d.ts' + const content = readDeclarations(`${distDir}/${dir}`)[file] + expect(content, dir).toContain(`from './Head.dev.${extension}'`) + expect(content, dir).toContain(`from './hmr/index.${extension}'`) + expect(content, dir).toContain(`import('./Head.dev.${extension}')`) + expect(content, dir).toContain(`import('./hmr/index.${extension}')`) + } + }) + + it('should keep `.js` specifiers, as `.cjs` in the CJS set', () => { + for (const dir of ['esm', 'cjs', 'internal']) { + const extension = dir === 'cjs' ? 'cjs' : 'js' + const file = dir === 'cjs' ? 'extended.d.cts' : 'extended.d.ts' + expect(readDeclarations(`${distDir}/${dir}`)[file], dir).toBe( + [ + `export { headMode } from './Head.dev.${extension}';`, + `export { joinPaths } from './nested/paths.${extension}';`, + `export type LazyPaths = typeof import('./nested/paths.${extension}');`, + '', + ].join('\n'), + ) + } + }) + + it('should resolve every relative specifier in the declarations', () => { + const rootNames = [ + `${distDir}/esm/specifiers.d.ts`, + `${distDir}/cjs/specifiers.d.cts`, + `${distDir}/internal/specifiers.d.ts`, + `${distDir}/esm/extended.d.ts`, + `${distDir}/cjs/extended.d.cts`, + `${distDir}/internal/extended.d.ts`, + ] + const program = ts.createProgram(rootNames, { + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, + noEmit: true, + skipLibCheck: false, + strict: true, + }) + const diagnostics = ts + .getPreEmitDiagnostics(program) + .map((diagnostic) => + ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'), + ) + expect(diagnostics).toEqual([]) + }) + it('should not change the other output when the option is off', async () => { const outDir = await buildVariant({ internalDeclarations: false }) diff --git a/packages/vite-config/src/index.ts b/packages/vite-config/src/index.ts index bd9b7c8f..42b55ff8 100644 --- a/packages/vite-config/src/index.ts +++ b/packages/vite-config/src/index.ts @@ -1,5 +1,7 @@ // @ts-check +import { statSync } from 'node:fs' +import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { defineConfig } from 'vite' import dts from 'vite-plugin-dts' import { externalizeDeps } from 'vite-plugin-externalize-deps' @@ -9,23 +11,92 @@ import type { Options } from './types.js' export type { Options } +// The source files that an extensionless relative specifier resolves to, in +// the order TypeScript tries them. +const sourceModuleSuffixes = ['.ts', '.tsx', '.d.ts', '.js', '.jsx'] + +const isFile = (path: string) => + statSync(path, { throwIfNoEntry: false })?.isFile() ?? false + +/** + * Looks up what a relative `specifier` points at in the source tree. + * + * Returns `'module'` for a module such as `.ts`, `'directory'` for + * a directory with an `index` module, and `undefined` when neither exists. + */ +function findSourceTarget(sourceDir: string, specifier: string) { + const target = resolve(sourceDir, specifier) + if (sourceModuleSuffixes.some((suffix) => isFile(`${target}${suffix}`))) { + return 'module' + } + if ( + sourceModuleSuffixes.some((suffix) => + isFile(join(target, `index${suffix}`)), + ) + ) { + return 'directory' + } + return undefined +} + function ensureImportFileExtension({ content, extension, + sourceDir, }: { content: string extension: string + /** Source directory of the module that the declaration was emitted for */ + sourceDir: string | undefined }) { + const addExtension = (specifier: string) => { + // Without a dot after the leading `./` and `../` segments + const extensionless = /^(?:\.\.?\/)+[^.]+$/.test(specifier) + // Already points at a script, e.g. `./foo.js` + const scriptExtension = /\.[cm]?[jt]sx?$/.test(specifier) + + // In the CJS set, `./foo.js` for `foo.ts` becomes `./foo.cjs`, because + // its declaration is `foo.d.cts`. Only TypeScript sources count: a `.js` + // source, with `allowJs` or with a hand-written `.d.ts`, is kept as + // written. + if (extension === 'cjs' && sourceDir && specifier.endsWith('.js')) { + const base = specifier.slice(0, -'.js'.length) + const target = resolve(sourceDir, base) + if (isFile(`${target}.ts`) || isFile(`${target}.tsx`)) { + return `${base}.cjs` + } + } + + const target = + sourceDir && !scriptExtension + ? findSourceTarget(sourceDir, specifier) + : undefined + + // e.g. `./hmr` for `hmr/index.ts` + if (target === 'directory') { + return `${specifier}/index.${extension}` + } + // e.g. `./foo` for `foo.ts`, or `./HeadContent.dev` for + // `HeadContent.dev.tsx`. A specifier with a dot that names no source + // module, such as `./data.json` or `./Comp.vue`, is kept as written. + if (extensionless || target === 'module') { + return `${specifier}.${extension}` + } + return specifier + } + // replace e.g. `import { foo } from './foo'` with `import { foo } from './foo.js'` content = content.replace( - /(im|ex)port\s[\w{}/*\s,]+from\s['"](?:\.\.?\/)+?[^.'"]+(?=['"];?)/gm, - `$&.${extension}`, + /((?:im|ex)port\s[\w{}/*\s,]+from\s['"])((?:\.\.?\/)+[^'"]+)(?=['"])/gm, + (_, statement: string, specifier: string) => + statement + addExtension(specifier), ) // replace e.g. `import('./foo')` with `import('./foo.js')` content = content.replace( - /import\(['"](?:\.\.?\/)+?[^.'"]+(?=['"];?)/gm, - `$&.${extension}`, + /(import\(['"])((?:\.\.?\/)+[^'"]+)(?=['"])/gm, + (_, statement: string, specifier: string) => + statement + addExtension(specifier), ) return content } @@ -44,11 +115,41 @@ export const tanstackViteConfig = (options: Options): UserConfig => { const cjs = options.cjs ?? true const internalDeclarationsDir = getInternalDeclarationsDir(options, outDir) + // Resolved Vite root, which `vite-plugin-dts` resolves `outDirs` and + // `entryRoot` against. + let root = process.cwd() + + /** + * Maps a declaration file written to `declarationsDir` back to the source + * directory of its module. Returns `undefined` when the file is outside + * `declarationsDir`. + */ + const getSourceDir = (declarationsDir: string, filePath: string) => { + const relativeDir = relative( + resolve(root, declarationsDir), + dirname(filePath), + ) + if ( + relativeDir === '..' || + relativeDir.startsWith(`..${sep}`) || + isAbsolute(relativeDir) + ) { + return undefined + } + return resolve(root, options.srcDir, relativeDir) + } + return defineConfig({ resolve: { tsconfigPaths: !options.tsconfigPath, }, plugins: [ + { + name: 'tanstack-vite-config:root', + configResolved(config) { + root = config.root + }, + }, externalizeDeps({ include: options.externalDeps ?? [], except: options.bundledDeps ?? [], @@ -79,7 +180,11 @@ export const tanstackViteConfig = (options: Options): UserConfig => { options.beforeWriteDeclarationFile?.(filePath, content) || content return { filePath, - content: ensureImportFileExtension({ content, extension: 'js' }), + content: ensureImportFileExtension({ + content, + extension: 'js', + sourceDir: getSourceDir(`${outDir}/esm`, filePath), + }), } }, afterDiagnostic: (diagnostics) => { @@ -110,6 +215,7 @@ export const tanstackViteConfig = (options: Options): UserConfig => { content: ensureImportFileExtension({ content, extension: 'cjs', + sourceDir: getSourceDir(`${outDir}/cjs`, filePath), }), } }, @@ -146,6 +252,7 @@ export const tanstackViteConfig = (options: Options): UserConfig => { content: ensureImportFileExtension({ content, extension: 'js', + sourceDir: getSourceDir(internalDeclarationsDir, filePath), }), } }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6c38a7dc..3b54e8fc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -370,6 +370,9 @@ importers: '@tanstack/vite-config': specifier: workspace:* version: link:../../packages/vite-config + typescript: + specifier: 'catalog:' + version: 6.0.2 vite: specifier: 'catalog:' version: 8.3.5(@types/node@24.19.2)(jiti@2.7.0)(yaml@2.9.1)