出错原因分析:

执行命令 npm run build 时出现以下错误提示:

vite v3.2.7 building for production...                                                                        11:22:34
transforming (3) src\main.ts
 WARN  Browserslist: caniuse-lite is outdated. Please run:                                                    11:22:34
  npx update-browserslist-db@latest
  Why you should do it regularly: https://github.com/browserslist/update-db#readme

transforming (4893) node_modules\stringify-entities\lib\constant\dangerous.js
<--- Last few GCs --->

[18396:0000021B91231000]    98038 ms: Mark-Compact 2030.5 (2088.3) -> 2022.8 (2088.5) MB, pooled: 6 MB, 882.47 / 0.00 ms  (average mu = 0.127, current mu = 0.031) allocation failure; scavenge might not succeed
[18396:0000021B91231000]    98942 ms: Mark-Compact 2030.8 (2088.5) -> 2023.1 (2088.8) MB, pooled: 6 MB, 852.52 / 0.00 ms  (average mu = 0.093, current mu = 0.057) allocation failure; scavenge might not succeed


<--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
----- Native stack trace -----

 1: 00007FF6B48CBA4B node::SetCppgcReference+16011
 2: 00007FF6B48353F8 SSL_get_quiet_shutdown+92008
 3: 00007FF6B53C2D81 v8::Isolate::ReportExternalAllocationLimitReached+65
 4: 00007FF6B53AFB86 v8::Function::Experimental_IsNopFunction+2918
 5: 00007FF6B51FB830 v8::internal::StrongRootAllocatorBase::StrongRootAllocatorBase+31552
 6: 00007FF6B51F54FD v8::internal::StrongRootAllocatorBase::StrongRootAllocatorBase+6157
 7: 00007FF6B51F0D95 v8::internal::ThreadIsolation::JitPageReference::Size+190789
 8: 00007FF6B4B6A30D BIO_ssl_shutdown+189
 9: 7FF8000000000000

解决办法:

方法一、

node --max_old_space_size=102400 ./node_modules/vite/bin/vite.js build

方法二、

set NODE_OPTIONS=--max-old-space-size=4096
npm run build

方法三、

打开 package.json,在 scripts 部分修改 build 脚本:

{
  "scripts": {
    "build": "set NODE_OPTIONS=--max-old-space-size=4096 && vite build"
  }
}

方法四、

优化依赖和 Vite 配置
移除不必要的依赖:如果有不再使用的包或库,建议将其卸载,这样可以减少构建时的内存消耗。

npm uninstall <package-name>

分析并优化构建配置:使用 vite-plugin-analyzer 插件分析打包大小,并找出冗余或不必要的部分。

npm install vite-plugin-analyzer --save-dev

然后在 vite.config.js 中添加:

import { visualizer } from 'rollup-plugin-visualizer';

export default {
  plugins: [
    visualizer({ open: true }),
  ],
};