jctaoo / vite-electron-esbuild-starter

⚡️The electron starter using Vite and esbuild to fast development.
MIT License
54 stars 7 forks source link

Using a Preload Script #51

Closed thekevinbrown closed 3 years ago

thekevinbrown commented 3 years ago

Hi there!

First off thanks for this starter, it's really helped me get going. I'm having some trouble getting a preload script working correctly though.

I followed the instructions in #49, which works during development just fine. But when I do yarn pack:mac, then run the built application, I get:

Unable to load preload script: [path to application]/Contents/Resources/app.asar/preload.js

I created a reproduction to make it easy to replicate: https://github.com/thekevinbrown/vite-electron-esbuild-starter/tree/preload-reproduction

How do I get the preload script to end up working in the built application?

thekevinbrown commented 3 years ago

Sorry for the noise, I figured it out!

I had added this to the build command:

elecrun build && vite build && esbuild src/main/preload.ts --platform=node --bundle --outfile=app/preload.js

The problem is that the built app/preload.js file had bundled the electron dependency. When you try to run it this way, it'll throw: "Electron failed to install correctly, please delete node_modules/electron and try installing again". This then produces the "could not load preload.js" error. But we don't actually want electron in the bundle, we want it to require('electron');. So I updated the command to:

elecrun build && vite build && esbuild src/main/preload.ts --platform=node --external:electron --bundle --outfile=app/preload.js

And now the built preload file is loaded correctly in the .asar and it works a treat.