vite.config.ts
16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// @ts-ignore
import { defineConfig } from "vite";
// @ts-ignore
import vue from "@vitejs/plugin-vue";
import { fileURLToPath, URL } from "node:url";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
// @ts-ignore
import viteCompression from "vite-plugin-compression";
import replace from "@rollup/plugin-replace";
import { vanillaExtractPlugin } from "@vanilla-extract/vite-plugin";
import { vanillaExtractPlugin as vanillaExtractEsbuildPlugin } from "@vanilla-extract/esbuild-plugin";
import wasm from "vite-plugin-wasm";
import * as esbuild from "esbuild";
// 修复 highlight.js 导入问题的插件
const fixHighlightJs = () => {
return {
name: "fix-highlight-js",
enforce: "pre" as const,
transform(code: string, id: string) {
if (
id.includes("@tdesign-vue-next/chat") ||
id.includes("highlight.js")
) {
const fixedCode = code
.replace(
/import\s+(\w+)\s+from\s+['"]highlight\.js['"]/g,
"import * as $1 from 'highlight.js'",
)
.replace(
/import\s+(\w+)\s+from\s+['"]highlight\.js\/lib\/index\.js['"]/g,
"import * as $1 from 'highlight.js'",
);
if (fixedCode !== code) {
return { code: fixedCode, map: null };
}
}
return null;
},
};
};
// 强制转换 BlockSuite 中的 modern accessor 语法并确保装饰器正确转换
const fixBlockSuiteAccessor = () => {
return {
name: "fix-blocksuite-accessor",
enforce: "pre" as const,
apply: "build" as const, // 明确只在 build 模式下应用,防止影响 dev
async transform(code: string, id: string) {
// 拦截 blocksuite 相关文件,且只处理代码文件,排除样式文件和 vanilla-extract 文件
if ((id.includes("@blocksuite") || id.includes("blocksuite")) &&
!id.endsWith(".css") &&
!id.endsWith(".css.ts") &&
(id.endsWith(".js") || id.endsWith(".ts") || id.endsWith(".mjs"))) {
const hasAccessor = code.includes("accessor ");
const hasDecorators = code.includes("@");
if (hasAccessor || hasDecorators) {
const result = await esbuild.transform(code, {
target: "es2020",
loader: "ts", // 强制使用 ts loader
tsconfigRaw: {
compilerOptions: {
experimentalDecorators: false,
useDefineForClassFields: false, // 必须为 false 以兼容 Lit 装饰器
},
},
});
return {
code: result.code,
map: result.map || null,
};
}
}
return null;
},
};
};
// 修复 CJS 模块在浏览器中报错 "module is not defined" 的问题,以及缺省导出问题
const fixModuleNotDefined = () => {
return {
name: "fix-module-not-defined",
enforce: "pre" as const,
apply: "serve" as const, // 关键修复:只在开发环境应用,构建环境交给 Rollup 官方插件
transform(code: string, id: string) {
if (!id.includes("node_modules")) return null;
// 特殊处理 debug 包:如果它包含 require 调用且导致报错,我们直接将其替换为一个空实现的 ESM 模块
// 这样可以彻底绕过 CommonJS/require 问题,代价是 Dev 模式下可能看不到 debug 日志
if (id.includes("node_modules/debug/") && code.includes("require")) {
return {
code: `export default function() { return function() {}; }`,
map: null
};
}
// 排除那些不需要处理或处理会出问题的包
if (id.includes("@blocksuite") || id.includes("@univerjs") || id.includes("onnxruntime-web") || id.includes("highlight.js") ||
id.includes("/react/") || id.includes("_react") || id.includes("/react-dom/") || id.includes("_react-dom")) return null;
// 检查是否是 CommonJS 模块
const isCjs = (code.includes("module.exports") || code.includes("exports.")) && !code.includes("export ");
if (isCjs) {
// 如果没有 default 导出,强制注入,并注入一个假的 require 避免浏览器报错
return {
code: `var module = { exports: {} }; var exports = module.exports; var require = function() { return {}; };\n${code}\nexport default (module.exports.default || module.exports);`,
map: null,
};
}
return null;
},
};
};
// 修复 CJS 模块没有默认导出或命名导出的问题
const fixProblematicCjsModules = (modules: Record<string, string[]>) => {
return {
name: "fix-problematic-cjs-modules",
enforce: "pre" as const,
// apply: "build" as const, // 移除此行,让其在 Dev 环境也生效以修复 lodash.ismatch 等问题
transform(code: string, id: string) {
if (!id.includes("node_modules") || id.includes("lodash-es")) return null;
const moduleName = Object.keys(modules).find(m => {
const normalizedId = id.replace(/\\/g, '/');
const pkgName = m.split('/')[0];
const subPath = m.includes('/') ? m.substring(m.indexOf('/') + 1) : '';
// 更加宽松但准确的匹配逻辑,处理 pnpm, cnpm 等各种 node_modules 结构
const isPkgMatch = normalizedId.includes(`/node_modules/${m}/`) ||
normalizedId.includes(`/node_modules/${pkgName}/`) ||
(normalizedId.includes(`.pnpm/`) && (normalizedId.includes(`/${pkgName.replace('/', '+')}@`) || normalizedId.includes(`/${pkgName}@`))) ||
normalizedId.includes(`node_modules/_${pkgName.replace('/', '+')}@`) ||
normalizedId.includes(`node_modules/_${pkgName}@`);
if (!isPkgMatch) return false;
// 如果指定了子路径(如 react/jsx-runtime),则还需匹配子文件名
if (subPath) {
return normalizedId.includes(`/${subPath}.js`) || normalizedId.includes(`/${subPath}.mjs`);
}
return true;
});
if (moduleName) {
const hasModuleExports = code.includes("module.exports");
const hasExports = code.includes("exports.");
// 注入 shims 保护层,确保 module, exports, require 在代码执行前被定义
const shims = `
var module = typeof module !== 'undefined' ? module : { exports: {} };
var exports = typeof exports !== 'undefined' ? exports : module.exports;
var require = typeof require !== 'undefined' ? require : function(id) {
if (id === 'react' || id === 'react-dom') {
// 对于 react 和 react-dom 的 require,返回一个空对象,因为我们已经通过 alias 进行了重定向
return {};
}
console.warn('require is not defined and was called for:', id);
return {};
};
`;
let extraExports = `\n// --- Injected by fix-problematic-cjs-modules ---\n`;
if (!code.includes("export default")) {
extraExports += `export var defaultExport = (typeof exports !== "undefined" && exports.default) || (typeof module !== "undefined" && module.exports && module.exports.default) || (typeof module !== "undefined" && module.exports) || exports;\n`;
extraExports += `export default defaultExport;\n`;
}
const namedExports = modules[moduleName];
if (namedExports) {
namedExports.forEach(exp => {
// 检查变量是否已经在代码中声明过(不论是否导出)
const isDeclared = new RegExp(`\\b(function|const|var|let|class)\\s+${exp}\\b`).test(code);
if (!code.includes(`export var ${exp}`)) {
if (isDeclared) {
extraExports += `export { ${exp} };\n`;
} else {
// 使用 var 避免 TDZ 错误
extraExports += `export var ${exp} = (typeof exports !== "undefined" && exports.${exp}) || (typeof module !== "undefined" && module.exports && module.exports.${exp});\n`;
}
}
});
}
return {
code: `${shims}\n${code}${extraExports}`,
map: null,
};
}
return null;
},
};
};
// @ts-ignore
import { visualizer } from "rollup-plugin-visualizer";
// https://vite.dev/config/
export default defineConfig(({ mode }: { mode: string }) => {
const BASE_URL = "https://ai.linkmed.cc";
// const BASE_URL = "http://localhost:8181"; // 本地后端地址
const isProd = mode === "production";
const isDev = mode === "development";
const shouldAnalyze = process.env.ANALYZE === "true";
return {
plugins: [
fixModuleNotDefined(),
fixProblematicCjsModules({
"lodash.ismatch": [],
"lodash.clonedeep": [],
"lodash.merge": [],
"extend": [],
"bytes": [],
"simple-xml-to-json": [],
"@braintree/sanitize-url": ["sanitizeUrl"],
"lz-string": ["decompressFromEncodedURIComponent", "compressToEncodedURIComponent"],
"vscode-jsonrpc/lib/common/cancellation": ["CancellationTokenSource", "CancellationToken"],
"vscode-jsonrpc/lib/common/events": ["Event", "Emitter"],
"file-saver": ["saveAs"]
}),
wasm(),
vanillaExtractPlugin({
identifiers: isDev ? "debug" : "short",
}),
vue(),
shouldAnalyze && isProd && visualizer({
open: true,
gzipSize: true,
brotliSize: true,
filename: "dist/stats.html",
}),
// fixHighlightJs(),
AutoImport({
resolvers: [ElementPlusResolver()],
imports: ["vue", "vue-router", "pinia", "vue-i18n"],
dts: isDev ? "src/auto-import.d.ts" : false,
}),
Components({
resolvers: [ElementPlusResolver()],
dts: isDev ? "src/components.d.ts" : false,
}),
isProd && viteCompression(),
replace({
"process.env.NODE_ENV": JSON.stringify(isProd ? "production" : "development"),
"mermaid.debug": "false",
preventAssignment: true,
}),
].filter(Boolean),
define: {
"import.meta.env.VITE_APP_BASE_URL": JSON.stringify(BASE_URL),
"import.meta.env.VITE_USE_TOS_DIRECT_UPLOAD": JSON.stringify(process.env.VITE_USE_TOS_DIRECT_UPLOAD ?? "true"),
"process.env.NODE_ENV": JSON.stringify(isProd ? "production" : "development"),
},
esbuild: {
target: "es2020",
include: /\.(ts|tsx|js|jsx)$/,
tsconfigRaw: {
compilerOptions: {
experimentalDecorators: false,
useDefineForClassFields: false,
},
},
},
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
"debug": fileURLToPath(new URL("./src/utils/mock-debug.ts", import.meta.url)), // 强行 Mock debug 包
"bind-event-listener": fileURLToPath(new URL("./src/utils/mock-bind-event-listener.ts", import.meta.url)), // 强行 Mock bind-event-listener 包
// 关键修复:只在生产打包时启用 React 强制重定向,且使用 $ 进行精确匹配
...(isProd ? {
"react-dom/client": fileURLToPath(new URL("./node_modules/react-dom/client.js", import.meta.url)),
"react/jsx-runtime": fileURLToPath(new URL("./node_modules/react/cjs/react-jsx-runtime.production.min.js", import.meta.url)),
"react/jsx-dev-runtime": fileURLToPath(new URL("./node_modules/react/cjs/react-jsx-runtime.development.js", import.meta.url)),
"react$": fileURLToPath(new URL("./node_modules/react/cjs/react.production.min.js", import.meta.url)),
"react-dom$": fileURLToPath(new URL("./node_modules/react-dom/cjs/react-dom.production.min.js", import.meta.url)),
} : {})
},
dedupe: [
"highlight.js",
"@univerjs/core",
"@univerjs/design",
"@univerjs/engine-render",
"@univerjs/engine-formula",
"@univerjs/ui",
"@univerjs/sheets",
"@univerjs/sheets-ui",
"@univerjs/sheets-formula",
"rxjs",
"vue",
"bind-event-listener",
"simple-xml-to-json",
"yjs",
"lib0",
"y-protocols",
"lit",
"lit-html",
"lit-element",
],
preserveSymlinks: false,
},
server: {
port: 5173,
open: true,
fs: {
strict: false,
},
proxy: {
"/api": {
target: BASE_URL,
changeOrigin: true,
rewrite: (path: string) => path.replace(/^\/api/, "/api"),
secure: false,
},
"/deepresearch": {
target: BASE_URL,
changeOrigin: true,
rewrite: (path: string) => path.replace(/^\/deepresearch/, "/deepresearch"),
secure: false,
},
},
},
build: {
outDir: "dist",
// 提升构建目标至 es2022,减少对 Class 和 Decorators 的重写,能有效避开 TDZ 报错
target: "es2022",
sourcemap: mode !== "production",
minify: "esbuild",
esbuild: {
drop: isProd ? ["console", "debugger"] : [],
legalComments: "none",
target: "es2022",
// 强制降级命名捕获组正则,兼容部分旧版 Safari(Issue #1008906)
// Safari 13/14 部分版本不支持命名捕获组,会抛出 "invalid group specifier name" 错误
supported: {
'named-capture-groups': false,
},
},
// 禁用压缩报告,大幅提升打包速度
reportCompressedSize: false,
chunkSizeWarningLimit: 2000,
// 增强 CJS 转换逻辑
commonjsOptions: {
transformMixedEsModules: true,
include: [/node_modules/],
ignoreTryCatch: true,
},
// 禁用模块预加载
modulePreload: {
polyfill: false,
},
rollupOptions: {
output: {
manualChunks(id: string) {
const normalizedId = id.replace(/\\/g, '/');
if (!normalizedId.includes("node_modules")) {
if (normalizedId.includes("/src/utils/mock-")) return "vendor";
return;
}
// 1. 基础框架包(极稳定且高频使用)
if (
normalizedId.includes("/node_modules/vue/") ||
normalizedId.includes("/node_modules/@vue/") ||
normalizedId.includes("/node_modules/pinia/") ||
normalizedId.includes("/node_modules/vue-router/") ||
normalizedId.includes("/node_modules/vue-i18n/") ||
normalizedId.includes("/node_modules/vue-demi/")
) {
return "vue-foundation";
}
// 2. UI 组件库(体积大但独立)
if (normalizedId.includes("/node_modules/element-plus/")) {
return "ui-framework";
}
// 3. 基础工具库
if (normalizedId.includes("/node_modules/lodash") ||
normalizedId.includes("/node_modules/rxjs")) {
return "utils-vendor";
}
// 其他复杂的业务包(Univer, BlockSuite, Mermaid 等)不再手动干预,让 Vite 自动分块。
// 这样可以最大程度保留它们各自的初始化顺序,避免 TDZ 报错。
},
},
},
},
optimizeDeps: {
include: [
"react",
"react-dom",
"react/jsx-runtime",
"react/jsx-dev-runtime",
"@blocksuite/affine",
"@blocksuite/store",
"@blocksuite/affine-model",
"react",
"react/jsx-runtime",
"react/jsx-dev-runtime",
"react-dom",
"react-dom/client",
"@volcengine/tos-sdk",
].filter(item => !isDev || !item.includes("@blocksuite")), // 如果是 Dev 模式,不要把 @blocksuite 强制 include,避免在预打包阶段绕过 vanilla-extract 插件
exclude: [
"pdfjs-dist",
// 避免在 optimizeDeps 预打包阶段处理 BlockSuite 样式文件(尤其是 *.css.ts),
// 否则 vanilla-extract 的 Vite 插件拿不到这些文件,导致 "No CSS for file xxx.css.ts" 报错
...(isDev
? [
"@blocksuite/affine",
"@blocksuite/store",
"@blocksuite/affine-model",
"@blocksuite/affine-fragment-outline",
]
: []),
],
esbuildOptions: {
treeShaking: true,
target: "es2020",
loader: {
".js": "ts",
},
plugins: [
vanillaExtractEsbuildPlugin(),
],
tsconfigRaw: {
compilerOptions: {
experimentalDecorators: false,
useDefineForClassFields: false,
},
},
define: {
"import.meta.vitest": "undefined",
},
},
},
worker: {
format: "es",
},
};
});