You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron中调用PowerShell时出现require未定义错误求助

解决Electron中"require is not defined"错误,实现PowerShell脚本调用

问题根源

你的错误核心是Electron v12+默认开启了Context Isolation(上下文隔离),即使设置了nodeIntegration: true,渲染进程也无法直接访问Node.js的require方法——上下文隔离会将主进程、预加载脚本和渲染进程的运行环境完全隔离开,直接在渲染进程脚本里调用require('jquery')或require('node-powershell')必然报错。

解决方案步骤

1. 修正主进程配置(main.js)

保持上下文隔离开启(安全最佳实践),关闭nodeIntegration,确保preload路径正确:

// main.js
const { app, BrowserWindow } = require('electron')
const path = require('path')

const createWindow = () => {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false, // 必须关闭,配合上下文隔离
      contextIsolation: true, // 默认开启,显式声明更清晰
      preload: path.join(__dirname, 'preload.js')
    }
  })

  mainWindow.loadFile('index.html')
  // mainWindow.webContents.openDevTools()
}

// 其余代码保持不变...

2. 重写预加载脚本(preload.js)

使用contextBridge安全地将PowerShell功能暴露给渲染进程,避免直接暴露Node.js模块:

// preload.js
const { contextBridge } = require('electron')
const powershell = require('node-powershell')

// 暴露封装好的PowerShell调用方法到window对象
contextBridge.exposeInMainWorld('electronAPI', {
  runPowerShellCommand: async (command) => {
    const ps = new powershell({
      executionPolicy: 'Bypass',
      noProfile: true
    })

    try {
      ps.addCommand(command)
      const output = await ps.invoke()
      return output
    } catch (err) {
      console.error(err)
      throw err
    } finally {
      ps.dispose()
    }
  }
})

// 版本替换逻辑保留
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const dependency of ['chrome', 'node', 'electron']) {
    replaceText(`${dependency}-version`, process.versions[dependency])
  }
})

3. 调整渲染进程脚本(PowerShell.js)

不再使用require,直接调用preload暴露的window.electronAPI,同时通过script标签引入jQuery:
首先修改index.html,引入jQuery和PowerShell.js:

<!-- index.html -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
    <!-- 引入本地jQuery -->
    <script src="./node_modules/jquery/dist/jquery.min.js"></script>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.

    <script src="./renderer.js"></script>
    <!-- 引入PowerShell.js -->
    <script src="./PowerShell.js"></script>
  </body>
</html>

然后修改PowerShell.js:

// PowerShell.js
$(document).ready(async () => {
  try {
    // 调用preload暴露的API执行PowerShell命令
    const output = await window.electronAPI.runPowerShellCommand("Roads? Where we're going, we don't need roads.")
    console.log(output)
  } catch (err) {
    console.error(err)
  }
})

4. 验证依赖安装

确保已经安装所有依赖:

npm install

关键说明

  • 上下文隔离:是Electron的安全机制,禁止渲染进程直接访问Node.js API,必须通过preload脚本的contextBridge暴露经过封装的功能,避免XSS攻击风险。
  • jQuery引入:直接在index.html里通过script标签引入本地jQuery,比在渲染进程里用require更符合浏览器环境的使用方式,也避免了Node.js模块的调用问题。

内容的提问来源于stack exchange,提问作者Mark Philpott

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:55:36