在 Electron 中,使用“typeof”会导致 TypeError: Cannot assign to read only property

Posted

技术标签:

【中文标题】在 Electron 中,使用“typeof”会导致 TypeError: Cannot assign to read only property【英文标题】:In Electron, using "typeof" causes TypeError: Cannot assign to read only property 【发布时间】:2018-04-11 08:28:22 【问题描述】:

我在这里得到了一个doozie。在Electron's 主进程中,我需要在下面的函数中使用ipcMain 设置事件处理程序。这使 main.js 文件更加精简。一切都很顺利,直到我编写了一些验证代码来确保用户传入一个对象。为此,我一直使用typeof,从来没有遇到过问题。但在 Electron 中,我得到了:

主进程发生 javascript 错误 - TypeError: Cannot 分配给对象'#'的只读属性'exports'

代码:

const ipcMain = require('electron');

function ipcSetup() 

  ipcMain.on('123', function(event, arg) 

    // this blows chunks...
    if(arg && typeof arg === 'object') 
      console.log(`All good....`);
    

    // and if you comment that out, this use of "typeof" does the same thing
    console.log(typeof arg);

    // and to eliminate 'arg' as the issue...
    let a = 1;
    console.log(typeof a); // expect 'number', get Exception

  );



module.exports = ipcSetup;

我不知道 Electron 是否使用 Object.definePropertyarg 设为只读,但 typeof 无论如何都不会在这里分配,我消除了 arg 所以这个错误没有意义。环境是 Node 8.2.1 上的 Electron 1.8.4,使用 electron-vue

【问题讨论】:

typeof 语法在主线程中运行良好。这可能是上下文或模块导入方式的问题。仍在努力寻找答案。 【参考方案1】:

如果你在另一个使用 ES6 导入/导出语法的模块中导入该模块,使用 typeof 显然会导致这种情况。我认为这是因为 webpack 不支持混合这两种语法。但是很有趣的是,如果你不使用 typeof 操作符,它也能正常工作……

【讨论】:

以上是关于在 Electron 中,使用“typeof”会导致 TypeError: Cannot assign to read only property的主要内容,如果未能解决你的问题,请参考以下文章

在 electron-forge + webpack 应用程序中使用 electron-builder 构建的应用程序显示空白屏幕

在 Electron + React 中使用静态资源

使用 Electron 在 Angular 2 应用程序中访问文件系统

在 Electron 应用程序中使用 console.log()

oracle数据库表频繁插入和删除,会导致用不到索引吗?

如何在 Electron 中使用 node_modules?