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

Electron+React+Vite+TS项目开启sandbox后预加载脚本加载失败

解决Electron-vite开启sandbox后预加载脚本import语法错误问题

问题原因

开启sandbox: true后,Electron的预加载脚本运行在受限的沙箱环境中,该环境默认不支持ES模块的import语法。而electron-vite默认可能将预加载脚本构建为ES模块(.mjs格式),导致出现SyntaxError: Cannot use import statement outside a module错误。

解决方案

1. 修改electron-vite配置,强制预加载脚本输出为CommonJS格式

在项目根目录的electron-vite.config.ts中,针对预加载脚本的构建配置,指定输出格式为CommonJS:

import { defineConfig } from 'electron-vite'
import { resolve } from 'path'

export default defineConfig({
  preload: {
    build: {
      rollupOptions: {
        input: {
          index: resolve(__dirname, 'src/preload/index.ts')
        },
        output: {
          // 强制输出为CommonJS格式
          format: 'cjs',
          entryFileNames: '[name].cjs'
        }
      }
    }
  },
  // 主进程、渲染进程的其他配置保持不变
  main: { /* ... */ },
  renderer: { /* ... */ }
})

2. 调整主进程中预加载脚本的路径

修改主进程代码中加载预加载脚本的路径,指向构建后生成的.cjs文件:

import { BrowserWindow, app } from 'electron'
import { resolve } from 'path'

function createWindow() {
  const mainWindow = new BrowserWindow({
    webPreferences: {
      sandbox: true,
      contextIsolation: true, // 开启sandbox时建议配合开启上下文隔离
      // 指向构建后的CommonJS格式预加载脚本
      preload: resolve(__dirname, '../out/preload/index.cjs')
    }
  })

  mainWindow.loadFile('index.html')
}

app.whenReady().then(createWindow)

3. 检查预加载脚本的TypeScript配置(可选)

如果项目使用TypeScript,确保预加载脚本的ts配置(如单独的tsconfig.preload.json)中module设置为CommonJS:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "outDir": "../out/preload",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src/preload/**/*"]
}

完成以上配置后,重新构建项目,预加载脚本就能在sandbox模式下正常加载,contextBridge、ipcRenderer等Electron安全API也能正常使用。

内容的提问来源于stack exchange,提问作者Carlos Eduardo Rocha Miranda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 17:48:16