解决: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” 的错误提示,但是程序运行没有丝毫问题,具体如下图所示:
以下根据网上找的资料进行修改;就是运行打包的时候把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
package.json
修改main
"main": "dist-electron/main/index.mjs",
这样就行了,然后重启即可。改动的就这四个文件
完成!控制台没有出现报错,完美!
我用的是开源项目:
https://gitee.com/yiming_chang/electron-pure-admin
参考资料: