问题描述
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 these
let 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 it
if (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.");
});
});