前端項目運行時,如果經(jīng)常運行慢,崩潰停止服務(wù),報如下錯誤:
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory (JavaScript堆內(nèi)存不足)

原因:
因為在 Node 中,通過JavaScript使用內(nèi)存時只能使用部分內(nèi)存(64位系統(tǒng):1.4 GB,32位系統(tǒng):0.7 GB),這個時候,如果前端項目非常的龐大,Webpack編譯時就會占用很多的系統(tǒng)資源,如果超出了V8引擎對Node默認的內(nèi)存限制大小時,就會產(chǎn)生內(nèi)存溢出的錯誤。
解決方案:
1,安裝依賴
?npm install cross-env increase-memory-limit
2,在package.json 里的 script 里進行配置
LIMIT是你想分配的內(nèi)存大小,這里的8192單位是M也就是8G,大小可根據(jù)情況而定。
? "scripts": {? ??
????????"limit": "cross-env LIMIT=8192 increase-memory-limit"?
????}
3,執(zhí)行一次 npm run limit ,然后重新啟動項目。
但是這時候,重新啟動會報錯,如圖:
'"node --max-old-space-size=8192"' 不是內(nèi)部或外部命令,也不是可運行的程序或批處理文件。

解決方法:
在項目的 node_modules/.bin 文件下找到所以的 *.cmd 文件,"%_prog%" 去掉 雙引號 %_prog%
可在 node_modules 同級下,寫一個fix-memory-limit.config.js文件進行批次處理。
// 運行項目前通過node執(zhí)行此腳本 (此腳本與 node_modules 目錄同級)
const fs = require('fs')
const path = require('path')
const wfPath = path.resolve(__dirname, './node_modules/.bin')
fs.readdir(wfPath, (err, files) => {
? if (err) {
? ? console.log(err)
? } else {
? ? if (files.length != 0) {
? ? ? files.forEach(item => {
? ? ? ? if (item.split('.')[1] === 'cmd') {
? ? ? ? ? replaceStr(`${wfPath}/${item}`, /"%_prog%"/, '%_prog%')
? ? ? ? }
? ? ? })
? ? }
? }
})
// 參數(shù):[文件路徑、 需要修改的字符串、修改后的字符串] (替換對應(yīng)文件內(nèi)字符串的公共函數(shù))
function replaceStr(filePath, sourceRegx, targetSrt) {
? fs.readFile(filePath, (err, data) => {
? ? if (err) {
? ? ? console.log(err)
? ? } else {
? ? ? let str = data.toString()
? ? ? str = str.replace(sourceRegx, targetSrt)
? ? ? fs.writeFile(filePath, str, err => {
? ? ? ? console.log(err)
? ? ? })
? ? }
? })
}
然后修改 package.json里的 script里的語句
先處理內(nèi)存溢出問題,然后再執(zhí)行js,進行替換
&& 運算符,(相繼執(zhí)行,只有前一個執(zhí)行成功才會執(zhí)行下一個)
"scripts": {
????????"limit": "cross-env LIMIT=8192 increase-memory-limit && node fix-memory-limit.config.js"
}