在做项目时,随着需求的不断增加,我们的代码文件会越来越大,但是在打包时,在 Node 中通过 JavaScript 使用内存的大小却是有限制的。于是,今天打算部署代码时,报错了:
<--- JS stacktrace --->
==== JS stack trace =========================================
0: ExitFrame [pc: 00007FF69790ABBD]
Security context: 0x01e6a86408d1
1: decode(aka decode) [000002AD02F874D1] [E:\vite-template\node_modules_rollup@2.40.0@rollup\dist\shared\rollup.js:~133] [pc=0000039464A55451](this=0x037824a004b1 ,0x017863480119 <Very long string[1502653]>)
2: decodedSourcemap(aka decodedSourcemap) [000002AD02F8A979] [E:\vite-template\node_modules_rollup@2.40.0@rollup\dist\shared\roll...
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
解决方案
node --max_old_space_size=1024000 ./node_modules/vite/bin/vite.js build
在网上找了以下解决方案:
- 升级node版本(未尝试:非必要,不升级,免得带来不兼容问题)
- 修改vite.config.ts里面的配置项:
sourcemap: false
。但是有时我们可能想在部署到dev环境里进行调试(有些场景在部署后才能发现),那关闭了sourcemap,就无法在部署环境进行调试了,也不推荐。 - 找了段修改的实例(并不起作用,cross-env找不到,即使安装了也没起作用,不知为何):
"scripts": {
"dev": "vite",
"build": "cross-env NODE_OPTIONS=--max_old_space_size=1024000 vite build",
"preview": "vite preview"
}
// 改进版也不起作用
"build": "set NODE_OPTIONS= --max_old_space_size=10240 && vite build",
- vite下面的issue讨论里面发现了点线索,如下(亲测可用):
node --max_old_space_size=1024000 ./node_modules/vite/bin/vite.js build
https://github.com/vitejs/vite/issues/2433#issuecomment-792914871
https://github.com/vitejs/vite/issues/2433#issuecomment-1159005523
既然原因找到了(node 中使用内存受限),自己的问题也解决了(放宽该限制),探索到此为止。
参考地址:
https://github.com/vitejs/vite/issues/2433
https://blog.csdn.net/sigoyis/article/details/108005283
https://blog.csdn.net/weixin_38883338/article/details/109346148#:~:text=FATAL%20ERROR%3A%20Ineffective%20mark-compacts%20near%20heap%20limit%20Allocation,%E5%8E%9F%E5%9B%A0%E6%98%AF%20JavaScript%E5%A0%86%E5%86%85%E5%AD%98%E4%B8%8D%E8%B6%B3%EF%BC%8CNode%20%E6%98%AF%E5%9F%BA%E4%BA%8EV8%E5%BC%95%E6%93%8E%EF%BC%8C%E5%9C%A8%20Node%20%E4%B8%AD%E9%80%9A%E8%BF%87%20JavaScript%20%E4%BD%BF%E7%94%A8%E5%86%85%E5%AD%98%E6%97%B6%E5%8F%AA%E8%83%BD%E4%BD%BF%E7%94%A8%E9%83%A8%E5%88%86%E5%86%85%E5%AD%98%EF%BC%8864%E4%BD%8D%E7%B3%BB%E7%BB%9F%E4%B8%8B%E7%BA%A6%E4%B8%BA1.4%20GB%EF%BC%89%EF%BC%8C%E5%A6%82%E6%9E%9C%E5%86%85%E5%AD%98%E4%B8%8D%E8%B6%B3%EF%BC%8C%E5%8F%AF%E4%BB%A5%E7%94%A8%E4%B8%8B%E9%9D%A2%E6%96%B9%E6%B3%95%E6%9D%A5%E6%94%BE%E5%AE%BDV8%E9%BB%98%E8%AE%A4%E7%9A%84%E5%86%85%E5%AD%98%E9%99%90%E5%88%B6%E3%80%82