問題描述
npm run serve啟動前端項目時,控制臺輸出下圖一堆的文字,JS stack trace ,
問題現象:
==== JS stack trace =========================================Security context: 0000017B93ACFB61 <JS Object>1: init_scope_vars [0000017B93A04381 <undefined>:~3382] [pc=0000021C499F308D] (this=000003B07C026939 <an AST_Function with map 000001FA502ACAB9>,nesting=3)2: visit [0000017B93A04381 <undefined>:~3246] [pc=0000021C499EFC85] (this=000003CB4FA172A1 <a TreeWalker with map 000001FA502AEB61>,node=000003B07C026939 <an AST_Function with map 000001FA502ACAB9>,descend=000003EF887DA4C9 <JS Func...FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
問題原因:
nodejs v8 內存溢出問題:因為Node中通過JavaScript使用內存時只能使用部分內存(64位系統:1.4 GB,32位系統:0.7 GB),如果前端項目比較大,Webpack編譯時就會占用很多的系統資源,一旦超出了V8引擎對Node默認的內存限制大小時,就會產生內存溢出的錯誤
解決辦法:
直接在項目下 新建一個index.js文件夾,然后再終端執行 node index.js,這樣做的意義是 在運行項目進行編譯時,由于要使用到node_module依賴中對應的插件和包,對每一個執行文件寫入一個相對大一點的內存空間,在調用node_module依賴里面的包得時候會執行bin文件去調取對應的包,給調用包分配一個較大的內存空間,以至于解決內存空間不足的問題
沒寫入之前
寫入之后
細節描述
下面就是 index.js文件的內容
#!/usr/bin/env node
const path = require('path');
const glob = require('glob');
const fs = require('fs');const maxOldSpaceSize = process.env.LIMIT || 10240;
const cwd = process.cwd() + path.sep;glob(path.join(cwd, "node_modules", ".bin", "*"), function (err, files) {files.forEach(file => {// readFileSync will crash on non-files. Skip over theselet stat = fs.lstatSync(fs.realpathSync(file));if (!stat.isFile()) {return;}if (file.indexOf('increase-memory-limit') >= 0) {return;}// build scripts will hand in LIMIT via cross-env// avoid updating it while we are running itif (file.indexOf('cross-env') >= 0) {return;}let contents = fs.readFileSync(file).toString();let lines = contents.split('\n')let patchedContents = "";for (var index = 0; index < lines.length; index++) {var line = lines[index];if (line.startsWith("if [") || line.startsWith("@IF") || line.indexOf ('has_node') !== -1) {patchedContents += line + "\n";} else {patchedContents += line.replace(/node(\.exe)?\b(?: \-\-max\-old\-space\-size\=[0-9]+)?/, `node$1 --max-old-space-size=${maxOldSpaceSize}`) + "\n";}}fs.writeFileSync(file, patchedContents);console.log(`'${file.replace(cwd, "")}'`, "written successfully.");});});