渲染进程require模块fs失败

13 min read

渲染进程require模块fs失败

d44f3a177ad548f9abb64bcc0bb58d51.png

打印出来的fs为一个空对象,

错误原因: webpack在打包时截胡了require(‘fs’),使其去找node_modules下的fs,其实是不存的。 解决方案如下:

const fs = window.require('fs')

在主进程main.js 设置

let windowConfig = { // 窗口配置程序运行窗口的大小
  width: 900,
  height: 700,
  webPreferences: {
    nodeIntegration: true, 
  },
}

Electronjs window.require not a function

从Electron 12开始,contextIsolation被默认为启用,这意味着除非contextIsolation为假,否则require()不能在渲染器过程中使用,更多信息见此链接

https://www.electronjs.org/docs/breaking-changes#default-changed-contextisolation-defaults-to-true

renderer进程使用require报错:Uncaught ReferenceError: window.require is not a function

解决:

// Create the browser window.
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {

            // Use pluginOptions.nodeIntegration, leave this alone
            // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
            nodeIntegration: true,
            contextIsolation: false,
        },

    })