返回 slidev
extendConfig.ts
根目录 / packages / slidev / node / vite / extendConfig.ts
1 import type { ResolvedSlidevOptions } from '@slidev/types'
2 import type { Plugin, UserConfig } from 'vite'
3 import { fileURLToPath, pathToFileURL } from 'node:url'
4 import { slash, uniq } from '@antfu/utils'
5 import { createResolve } from 'mlly'
6 import { join } from 'pathe'
7 import { mergeConfig } from 'vite'
8 import { isInstalledGlobally, resolveImportPath, toAtFS } from '../resolver'
9
10 const RE_SLIDEV_CLIENT = /^@slidev\/client$/
11 const RE_SLIDEV_CLIENT_SUBPATH = /^@slidev\/client\/(.*)/
12 const RE_SLIDEV_VIRTUAL = /^#slidev\/(.*)/
13 const RE_MONACO_EDITOR = /\/monaco-editor(?:-core)?\//
14
15 const INCLUDE_GLOBAL = [
16 '@fix-webm-duration/fix',
17 '@typescript/ata',
18 'file-saver',
19 'lz-string',
20 'recordrtc',
21 'typescript',
22 'yaml',
23 'pptxgenjs',
24 'ansis',
25 ]
26
27 const INCLUDE_LOCAL = INCLUDE_GLOBAL.map(i => `@slidev/cli > @slidev/client > ${i}`)
28
29 // @keep-sorted
30 const EXCLUDE_GLOBAL = [
31 '@antfu/utils',
32 '@shikijs/magic-move/vue',
33 '@shikijs/monaco',
34 '@shikijs/vitepress-twoslash/client',
35 '@slidev/client',
36 '@slidev/client/constants',
37 '@slidev/client/context',
38 '@slidev/client/logic/dark',
39 '@slidev/parser',
40 '@slidev/parser/core',
41 '@slidev/rough-notation',
42 '@slidev/types',
43 '@unhead/vue',
44 '@unocss/reset',
45 '@vueuse/core',
46 '@vueuse/math',
47 '@vueuse/motion',
48 '@vueuse/shared',
49 'drauu',
50 'floating-vue',
51 'fuse.js',
52 'mermaid',
53 'monaco-editor',
54 'shiki',
55 'shiki/core',
56 'vue-demi',
57 'vue-router',
58 'vue',
59 ]
60
61 const EXCLUDE_LOCAL = EXCLUDE_GLOBAL
62
63 const ASYNC_MODULES = [
64 'file-saver',
65 'vue',
66 '@vue',
67 ]
68
69 export function createConfigPlugin(options: ResolvedSlidevOptions): Plugin {
70 const resolveClientDep = createResolve({
71 // Same as Vite's default resolve conditions
72 conditions: [
73 'import',
74 'module',
75 'browser',
76 'default',
77 options.mode === 'build'
78 ? 'production'
79 : 'development',
80 ],
81 url: pathToFileURL(options.clientRoot),
82 })
83 return {
84 name: 'slidev:config',
85 async config(config) {
86 const injection: UserConfig = {
87 define: options.utils.define,
88 resolve: {
89 alias: [
90 {
91 find: RE_SLIDEV_CLIENT,
92 replacement: `${toAtFS(options.clientRoot)}/index.ts`,
93 },
94 {
95 find: RE_SLIDEV_CLIENT_SUBPATH,
96 replacement: `${toAtFS(options.clientRoot)}/$1`,
97 },
98 {
99 find: RE_SLIDEV_VIRTUAL,
100 replacement: '/@slidev/$1',
101 },
102 {
103 find: 'vue',
104 replacement: await resolveImportPath('vue/dist/vue.esm-bundler.js', true),
105 },
106 ...(isInstalledGlobally.value
107 ? await Promise.all(INCLUDE_GLOBAL.map(async dep => ({
108 find: dep,
109 replacement: fileURLToPath(await resolveClientDep(dep)),
110 })))
111 : []
112 ),
113 ],
114 dedupe: ['vue'],
115 },
116 optimizeDeps: isInstalledGlobally.value
117 ? {
118 exclude: EXCLUDE_GLOBAL,
119 include: INCLUDE_GLOBAL,
120 }
121 : {
122 // We need to specify the full deps path for non-hoisted modules
123 exclude: EXCLUDE_LOCAL,
124 include: INCLUDE_LOCAL,
125 },
126 css: {
127 postcss: {
128 plugins: [
129 await import('postcss-nested').then(r => (r.default || r)()) as any,
130 ],
131 },
132 },
133 server: {
134 fs: {
135 strict: true,
136 allow: uniq([
137 options.userWorkspaceRoot,
138 options.clientRoot,
139 // Special case for PNPM global installation
140 isInstalledGlobally.value
141 ? slash(options.cliRoot).replace(/\/\.pnpm\/.*$/gi, '')
142 : options.cliRoot,
143 ...options.roots,
144 ]),
145 },
146 },
147 publicDir: join(options.userRoot, 'public'),
148 build: {
149 rollupOptions: {
150 output: {
151 chunkFileNames(chunkInfo) {
152 const DEFAULT = 'assets/[name]-[hash].js'
153
154 // Already handled in manualChunks
155 if (chunkInfo.name.includes('/'))
156 return DEFAULT
157
158 // Over 60% of the chunk is slidev client code, we put it into slidev chunk
159 if (chunkInfo.moduleIds.filter(i => isSlidevClient(i)).length > chunkInfo.moduleIds.length * 0.6)
160 return 'assets/slidev/[name]-[hash].js'
161
162 // Monaco Editor
163 if (chunkInfo.moduleIds.filter(i => i.match(RE_MONACO_EDITOR)).length > chunkInfo.moduleIds.length * 0.6)
164 return 'assets/monaco/[name]-[hash].js'
165
166 return DEFAULT
167 },
168 manualChunks(id) {
169 if (id.startsWith('/@slidev-monaco-types/') || id.includes('/@slidev/monaco-types') || id.endsWith('?monaco-types&raw'))
170 return 'monaco/bundled-types'
171 if (id.includes('/shiki/') || id.includes('/@shikijs/'))
172 return `modules/shiki`
173 if (id.startsWith('~icons/'))
174 return 'modules/unplugin-icons'
175 // It seems that moving slides out will breaks the production build
176 // Would need to find a better way to handle this
177 // const slideMatch = id.match(/\/@slidev\/slides\/(\d+)/)
178 // if (slideMatch && !id.includes('.frontmatter'))
179 // return `slides/${slideMatch[1]}`
180
181 const matchedAsyncModule = ASYNC_MODULES.find(i => id.includes(`/node_modules/${i}`))
182 if (matchedAsyncModule)
183 return `modules/${matchedAsyncModule.replace('@', '').replace('/', '-')}`
184 },
185 },
186 },
187 },
188 cacheDir: isInstalledGlobally.value
189 ? join(options.cliRoot, 'node_modules/.vite')
190 : undefined,
191 }
192
193 function isSlidevClient(id: string) {
194 return id.includes('/@slidev/') || id.includes('/slidev/packages/client/') || id.includes('/@vueuse/')
195 }
196
197 // function getNodeModuleName(path: string) {
198 // const nodeModuelsMatch = [...path.matchAll(/node_modules\/(@[^/]+\/[^/]+|[^/]+)\//g)]
199 // if (nodeModuelsMatch.length)
200 // return nodeModuelsMatch[nodeModuelsMatch.length - 1][1]
201 // }
202
203 return mergeConfig(injection, config)
204 },
205 configureServer(server) {
206 // serve our index.html after vite history fallback
207 return () => {
208 server.middlewares.use(async (req, res, next) => {
209 if (req.url === '/index.html') {
210 let html: string
211 try {
212 // Inject `/@vite/client` and run other plugins' `transformIndexHtml` hooks.
213 // Vite 8 relies on `/@vite/client` to install `define` globals in the browser.
214 html = await server.transformIndexHtml(req.url, options.utils.indexHtml, req.originalUrl)
215 }
216 catch (e) {
217 return next(e)
218 }
219
220 const headers = server.config.server.headers ?? {}
221
222 for (const header in headers) {
223 res.setHeader(header, headers[header]!)
224 }
225
226 res.setHeader('Content-Type', 'text/html')
227 res.statusCode = 200
228 res.end(html)
229 return
230 }
231 next()
232 })
233 }
234 },
235 }
236 }
237
237 lines TYPESCRIPT