本文解决 electron-vue 项目中因 Node.js 版本过低导致 Object.fromEntries 方法未定义的问题。通过安装 polyfill-object.fromentries 依赖,并在 .electron-vue/dev-client.js 中引入,可修复运行时报错。文章同时解析了该 ES2019 方法及 polyfill 实现原理,帮助开发者理解兼容方案。
1. 背景
近期在开发基于 electron-vue 框架的桌面应用时,参照官方文档执行相关操作后,遇到了 Object.fromEntries is not a function 的错误提示。

2. 解决方案
2.1 第一步:安装依赖
在项目根目录下,通过终端执行以下命令来安装必要的 polyfill 依赖包:
npm i polyfill-object.fromentries2.2 第二步:项目中引入
打开项目中的 /.electron-vue/dev-client.js 文件,在代码中引入刚才安装的插件。完整的配置代码如下:
const hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true')
// 引入插件
import 'polyfill-object.fromentries';
hotClient.subscribe(event => {
/**
* Reload browser when HTMLWebpackPlugin emits a new index.html
*
* Currently disabled until jantimon/html-webpack-plugin#680 is resolved.
* https://github.com/SimulatedGREG/electron-vue/issues/437
* https://github.com/jantimon/html-webpack-plugin/issues/680
*/
// if (event.action === 'reload') {
// window.location.reload()
// }
/**
* Notify `mainWindow` when `main` process is compiling,
* giving notice for an expected reload of the `electron` process
*/
if (event.action === 'compiling') {
document.body.innerHTML += `
<style>
#dev-client {
background: #4fc08d;
border-radius: 4px;
bottom: 20px;
box-shadow: 0 4px 5px 0 rgba(0, 0, 0, 0.14), 0 1px 10px 0 rgba(0, 0, 0, 0.12), 0 2px 4px -1px rgba(0, 0, 0, 0.3);
color: #fff;
font-family: 'Source Sans Pro', sans-serif;
left: 20px;
padding: 8px 12px;
position: absolute;
}
</style>
<div id="dev-client">
Compiling Main Process...
</div>
`
}
})3. 组件详解
Object.fromEntries() 是 ECMAScript 2019 标准中新增的静态方法,主要作用是将键值对列表(例如数组)转换为对象。若当前运行环境不支持此方法,可通过引入 polyfill 来提供兼容功能。
具体而言,Object.fromEntries() 接收一个二维数组作为参数:第一层数组中的元素表示键名,第二层表示对应的键值,最终返回由这些键值对构成的对象。示例如下:
const arr = [
['name', 'Alice'],
['age', 18],
['gender', 'female']
];
const obj = Object.fromEntries(arr);
console.log(obj); // { name: 'Alice', age: 18, gender: 'female' }当运行环境不支持 Object.fromEntries() 时,可采用以下 polyfill 代码实现相同功能:
if (!Object.fromEntries) {
Object.fromEntries = function(entries) {
if (!entries || !entries[Symbol.iterator]) {
throw new Error('Object.fromEntries() requires an iterable argument');
}
const obj = {};
for (let [key, value] of entries) {
obj[key] = value;
}
return obj;
};
}该 polyfill 函数首先检测当前环境是否原生支持 Object.fromEntries()。若不支持,则定义同名函数并实现其逻辑。实现过程中利用了 for…of 循环配合解构赋值语法,遍历键值对列表并将其转换为对象。
至此,关于 electron-vue 运行报错 Object.fromEntries is not a function 的解决方法介绍完毕。如需了解更多相关 electron-vue 报错处理内容,欢迎查阅本站往期文章或继续浏览后续教程,感谢支持!