Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/declaration-import-extensions.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions integrations/internal-declarations/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
},
"devDependencies": {
"@tanstack/vite-config": "workspace:*",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "catalog:"
}
Expand Down
1 change: 1 addition & 0 deletions integrations/internal-declarations/snap/cjs/Head.dev.d.cts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare const headMode: "dev";
3 changes: 3 additions & 0 deletions integrations/internal-declarations/snap/cjs/extended.d.cts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { headMode } from './Head.dev.cjs';
export { joinPaths } from './nested/paths.cjs';
export type LazyPaths = typeof import('./nested/paths.cjs');
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type HmrStyle = 'full' | 'partial';
4 changes: 4 additions & 0 deletions integrations/internal-declarations/snap/cjs/specifiers.d.cts
Original file line number Diff line number Diff line change
@@ -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;
1 change: 1 addition & 0 deletions integrations/internal-declarations/snap/esm/Head.dev.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare const headMode: "dev";
3 changes: 3 additions & 0 deletions integrations/internal-declarations/snap/esm/extended.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { headMode } from './Head.dev.js';
export { joinPaths } from './nested/paths.js';
export type LazyPaths = typeof import('./nested/paths.js');
1 change: 1 addition & 0 deletions integrations/internal-declarations/snap/esm/hmr/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type HmrStyle = 'full' | 'partial';
4 changes: 4 additions & 0 deletions integrations/internal-declarations/snap/esm/specifiers.d.ts
Original file line number Diff line number Diff line change
@@ -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;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare const headMode: "dev";
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { headMode } from './Head.dev.js';
export { joinPaths } from './nested/paths.js';
export type LazyPaths = typeof import('./nested/paths.js');
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type HmrStyle = 'full' | 'partial';
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 2 additions & 0 deletions integrations/internal-declarations/src/Head.dev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// A module whose base name contains a dot.
export const headMode = 'dev' as const
5 changes: 5 additions & 0 deletions integrations/internal-declarations/src/extended.ts
Original file line number Diff line number Diff line change
@@ -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')
2 changes: 2 additions & 0 deletions integrations/internal-declarations/src/hmr/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Imported through its directory, `./hmr`.
export type HmrStyle = 'full' | 'partial'
7 changes: 7 additions & 0 deletions integrations/internal-declarations/src/specifiers.ts
Original file line number Diff line number Diff line change
@@ -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
56 changes: 56 additions & 0 deletions integrations/internal-declarations/tests/build.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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<string, Match>;')
expect(internal['index.d.ts']).toContain('_strictParams')
Expand Down Expand Up @@ -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 })

Expand Down
117 changes: 112 additions & 5 deletions packages/vite-config/src/index.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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 `<specifier>.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
}
Expand All @@ -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 ?? [],
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -110,6 +215,7 @@ export const tanstackViteConfig = (options: Options): UserConfig => {
content: ensureImportFileExtension({
content,
extension: 'cjs',
sourceDir: getSourceDir(`${outDir}/cjs`, filePath),
}),
}
},
Expand Down Expand Up @@ -146,6 +252,7 @@ export const tanstackViteConfig = (options: Options): UserConfig => {
content: ensureImportFileExtension({
content,
extension: 'js',
sourceDir: getSourceDir(internalDeclarationsDir, filePath),
}),
}
},
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading