Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

electron渲染进程报错require is not defined,搜索解决方案无果

如题,运行环境为

Windows 10 x64 20H2,
Electron v11.1.1,
Chromium v87.0.4280.88,
Node v12.18.3

项目主进程main.js如下:


const { app, BrowserWindow, Menu } = require('electron')
const { chmod } = require('fs')
const { join } = require('path')
const { pathToFileURL } = require('url')
const { runInContext } = require('vm')

function createWindow () {
  const win = new BrowserWindow({
    width: 980,
    height: 580,
    //frame: false,
    resizable: false,
    webPreferences: {
      nodeIntegration: true,
      preload: join(__dirname,'renderer.js')
    }
  })

  win.loadFile('interface/index.html')
}

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
})

//Menu.setApplicationMenu(null)

渲染进程renderer.js如下:


window.electron=require('electron');
const exec = require('child_process').exec;
const fs=require('fs');
const {ipcRenderer} = require('electron').ipcRenderer;
const { windowsStore } = require('process');
const { Script } = require('vm');
const { electron } = window.electron;

function RunKit()//运行项目根目录的main.exe
{
    var cmd = "main.exe";    
    exec(cmd, function(error, stdout, stderr) {  console.log(stdout);  });    
}

function Order(Args)
{
    
    fs.writeFile('file.in',Args);
}

命令行输入npm start运行时控制台出现如下报错:

Uncaught ReferenceError: require is not defined at renderer.js:2
Uncaught ReferenceError: Cannot access 'exec' before initialization at RunKit (renderer.js:13)

后一个报错估计是前一个报错导致解释中止导致的,那么前一个报错究竟是为什么会产生?我对照着百度上说的检查了main.js中的nodeIntegration: true是没问题的。已经在这里卡了两天了,求大佬解救。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...