首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ Electron / 文章详情

解决:electron Unable to load preload script: \dist-electron\preload\index.js (anonymous) @ node:electron/js2c/renderer_init:2

Sonder
2024-11-25
2598字
6分钟
浏览 (168)

运行项目时,控制台出现 “Unable to load preload script” 的错误提示,但是程序运行没有丝毫问题,具体如下图所示:

image.png

以下根据网上找的资料进行修改;就是运行打包的时候把dist-electron里面的js文件改成mjs即可。

vite.config.ts

entry: "electron/main/index.ts"entry: "electron/preload/index.ts"vite->build->rollupOptions加这段话:

复制代码
output: {
 format: "esm",
 entryFileNames: "[name].mjs"
}

下面是完整代码:

复制代码
// plugins
electron([
 {
   // Main-Process entry file of the Electron App.
   entry: "electron/main/index.ts",
   onstart(options) {
     if (process.env.VSCODE_DEBUG) {
       console.log(
         /* For `.vscode/.debug.script.mjs` */ "[startup] Electron App"
       );
     } else {
       options.startup();
     }
   },
   vite: {
     build: {
       sourcemap,
       minify: isBuild,
       outDir: "dist-electron/main",
       rollupOptions: {
         output: {
           format: "esm",
           entryFileNames: "[name].mjs"
         },
         external: Object.keys(
           "dependencies" in pkg ? pkg.dependencies : {}
         )
       }
     }
   }
 },
 {
   entry: "electron/preload/index.ts",
   onstart(options) {
     // Notify the Renderer-Process to reload the page when the Preload-Scripts build is complete,
     // instead of restarting the entire Electron App.
     options.reload();
   },
   vite: {
     build: {
       sourcemap: sourcemap ? "inline" : undefined,
       minify: isBuild,
       outDir: "dist-electron/preload",
       rollupOptions: {
         external: Object.keys(
           "dependencies" in pkg ? pkg.dependencies : {}
         ),
         output: {
           format: "esm",
           entryFileNames: "[name].mjs"
         }
       }
     }
   }
 }
]),

electron 文件夹

electron\main\index.ts

复制代码
win = new BrowserWindow({
 width: 1024,
 height: 768,
 minWidth: 1024,
 minHeight: 768,
 title: "xxxx",
 icon: join(process.env.PUBLIC, "favicon.ico"),
 webPreferences: {
   preload: join(__dirname, "../preload/index.mjs"),
   // Warning: Enable nodeIntegration and disable contextIsolation is not secure in production
   // Consider using contextBridge.exposeInMainWorld
   // Read more on https://www.electronjs.org/docs/latest/tutorial/context-isolation
   nodeIntegration: true,
   contextIsolation: false
 }
});

electron\preload\index.ts

image.png

package.json

修改main

复制代码
"main": "dist-electron/main/index.mjs",

这样就行了,然后重启即可。改动的就这四个文件

image.png

完成!控制台没有出现报错,完美!

image.png

我用的是开源项目:

https://gitee.com/yiming_chang/electron-pure-admin

参考资料:

  1. GitHub Issues with v28
  2. 提问题人的解决项目地址 WeakAuras-Companion
下一篇 / electron-builder.json5 打包动态设置包名

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)