跳至内容
本页内容

预加载脚本代码不拆分

无论主进程是否启用 Node.js,预加载脚本都支持加载 electron 模块,所以我们需要以 cjs 格式构建它。

ts
import { ipcRenderer } from 'electron'
// ↓↓↓↓ Build with `cjs` format ↓↓↓↓
const { ipcRenderer } = require('electron')

Rollupcjs 格式构建代码时,它会自动将代码拆分成多个块,并使用 require() 加载它们,并且在主进程 nodeIntegration: false 时使用 require() 加载其他模块会发生错误。所以我们需要配置 Rollup 在构建时不要拆分代码,以确保它在 nodeIntegration: false 情况下正常工作。

注意

nodeIntegration: true 的情况下,我们不必担心这个问题!

中文

无论主进程开启 Node.js 与否,预加载脚本都支持加载 electron 模块,所以我们需要 cjs 格式构建它。

Rollupcjs 格式构建代码时会自动将代码拆分成多个 chunk,并且使用 require() 加载它们,并且在主进程 nodeIntegration: false 时使用 require() 加载其他模块会发生错误。所以我们需要配置 Rollup 构建时候不要拆分代码,以确保在 nodeIntegration: false 情况下正常工作。

nodeIntegration: true 情况下,我们不必为此担心!

ts
// vite.config.ts
import electron from 'vite-plugin-electron'

export default {
  plugins: [
    electron([
      {
        entry: 'electron/main/index.ts',
      },
      {
        entry: 'electron/preload/index.ts',
        onstart({ reload }) {
          reload()
        },
        vite: {
          build: {
            outDir: 'dist-electron/preload',
            rollupOptions: {
              output: {
                // Disable Preload scripts code split
                inlineDynamicImports: true,
              },
            },
          },
        },
      }
    ]),
  ],
}