Open History to see the last commit
1import { defineConfig, mergeConfig } from 'vite'
2import { externalizeDeps } from 'vite-plugin-externalize-deps'
3import tsconfigPaths from 'vite-tsconfig-paths'
4import dts from 'vite-plugin-dts'
5import type { Options } from '@tanstack/vite-config'
6β
7function ensureImportFileExtension({
8 content,
9 extension,
10}: {
11 content: string
12 extension: string
13}) {
14 // replace e.g. `import { foo } from './foo'` with `import { foo } from './foo.js'`
15 content = content.replace(
16 /(im|ex)port\s[\w{}/*\s,]+from\s['"](?:\.\.?\/)+?[^'"]+(?=['"];?)/gm,
17 (specifier) =>
18 /\.(?:[cm]?js|json)$/.test(specifier)
19 ? specifier
20 : `${specifier}.${extension}`,
21 )
22β
23 // replace e.g. `import('./foo')` with `import('./foo.js')`
24 content = content.replace(
25 /import\(['"](?:\.\.?\/)+?[^'"]+(?=['"];?)/gm,
26 (specifier) =>
27 /\.(?:[cm]?js|json)$/.test(specifier)
28 ? specifier
29 : `${specifier}.${extension}`,
30 )
31 return content
32}
33β
34const config = defineConfig({
35 // fix from https://github.com/vitest-dev/vitest/issues/6992#issuecomment-2509408660
36 resolve: {
37 conditions: ['@tanstack/custom-condition'],
38 },
39})
40β
41// copy from @tanstack/config/vite with changes:
42// - build - lib - fileName: [name.mjs]
43// - rollup - output - preserveModulesRoot: src
44export const tanstackViteConfig = (options: Options) => {
45 const outDir = options.outDir ?? 'dist'
46 const cjs = options.cjs ?? true
47β
48 return defineConfig({
49 plugins: [
50 externalizeDeps({ include: options.externalDeps ?? [] }),
51 tsconfigPaths({
52 projects: options.tsconfigPath ? [options.tsconfigPath] : undefined,
53 }),
54 dts({
55 outDir,
56 entryRoot: options.srcDir,
57 include: options.srcDir,
58 exclude: options.exclude,
59 tsconfigPath: options.tsconfigPath,
60 compilerOptions: {
61 module: 99, // ESNext
62 declarationMap: false,
63 },
64 beforeWriteFile: (filePath, content) => {
65 return {
66 filePath,
67 content: ensureImportFileExtension({ content, extension: 'js' }),
68 }
69 },
70 afterDiagnostic: (diagnostics) => {
71 if (diagnostics.length > 0) {
72 console.error('Please fix the above type errors')
73 process.exit(1)
74 }
75 },
76 }),
77 ],
78 build: {
79 outDir,
80 minify: false,
81 sourcemap: true,
82 lib: {
83 entry: options.entry,
84 formats: cjs ? ['es', 'cjs'] : ['es'],
85 fileName: () => '[name].mjs',
86 },
87 rollupOptions: {
88 output: {
89 preserveModules: true,
90 preserveModulesRoot: 'src',
91 },
92 },
93 },
94 })
95}
96β
97export default mergeConfig(
98 config,
99 tanstackViteConfig({
100 cjs: false,
101 entry: ['./src/index.ts', './src/internal.ts'],
102 exclude: ['src/**/__tests__/**', 'src/**/__test__/**'],
103 srcDir: './src',
104 tsconfigPath: 'tsconfig.prod.json',
105 }),
106)