Skip to content

Commit f220843

Browse files
authored
chore: merge kitchensink's Vite config into CLI config (#624)
1 parent 17927c0 commit f220843

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,88 @@
11
import {defineCliConfig} from 'sanity/cli'
2+
import {
3+
type ConfigEnv,
4+
type Plugin,
5+
type PluginOption,
6+
type UserConfig,
7+
type UserConfigExport,
8+
} from 'vite'
29

310
export default defineCliConfig({
411
app: {
512
organizationId: 'oblZgbTFj',
613
entry: './src/App.tsx',
714
id: 'wkyoigmzawwnnwx458zgoh46',
815
},
16+
// Extend Sanity CLI's internal Vite config with the app's Vite config
17+
vite: async (prev: UserConfig) => {
18+
const {default: viteConfigFactory} = (await import('./vite.config.ts')) as {
19+
default: UserConfigExport
20+
}
21+
22+
const mode = process.env['NODE_ENV'] === 'production' ? 'production' : 'development'
23+
const command: ConfigEnv['command'] = mode === 'production' ? 'build' : 'serve'
24+
const env: ConfigEnv = {mode, command}
25+
26+
const projectConfigMaybe =
27+
typeof viteConfigFactory === 'function' ? viteConfigFactory(env) : viteConfigFactory
28+
const projectConfig = (await Promise.resolve(projectConfigMaybe)) as UserConfig
29+
30+
// Merge plugins without duplicates and avoid double React Refresh injection
31+
const flattenPlugins = (
32+
input: PluginOption | PluginOption[] | undefined,
33+
): import('vite').Plugin[] => {
34+
const result: import('vite').Plugin[] = []
35+
const push = (value: unknown) => {
36+
if (!value) return
37+
if (Array.isArray(value)) {
38+
value.forEach(push)
39+
return
40+
}
41+
const maybe = value as Partial<Plugin>
42+
if (typeof maybe === 'object' && maybe && 'name' in maybe) {
43+
result.push(maybe as Plugin)
44+
}
45+
}
46+
push(input as unknown)
47+
return result
48+
}
49+
50+
const prevPlugins = flattenPlugins(prev.plugins)
51+
const projectPlugins = flattenPlugins(projectConfig.plugins)
52+
53+
const projectHasReact = projectPlugins.some((p) => /react|refresh/i.test(p.name))
54+
const filteredPrev = projectHasReact
55+
? prevPlugins.filter((p) => !/react|refresh/i.test(p.name))
56+
: prevPlugins
57+
58+
const seen = new Set<string>()
59+
const mergedPlugins = [...projectPlugins, ...filteredPrev].filter((p) => {
60+
if (!p.name) return true
61+
if (seen.has(p.name)) return false
62+
seen.add(p.name)
63+
return true
64+
})
65+
66+
return {
67+
...prev,
68+
...projectConfig,
69+
plugins: mergedPlugins,
70+
resolve: {
71+
...prev.resolve,
72+
...projectConfig.resolve,
73+
alias: {
74+
...(prev.resolve?.alias ?? {}),
75+
...(projectConfig.resolve?.alias ?? {}),
76+
},
77+
},
78+
define: {
79+
...prev.define,
80+
...(projectConfig.define ?? {}),
81+
},
82+
server: {
83+
...prev.server,
84+
...(projectConfig.server ?? {}),
85+
},
86+
}
87+
},
988
})

0 commit comments

Comments
 (0)