How to use esm with electron 16?
When I make the type in package.json to module, the script electron . doesnt work well.
{
"name": "electronapp",
"version": "1.0.0",
"main": "main.js",
"type": "module",
...
}
I stumbled upon the same problem when trying to create a new project with Vue 3 and Vite in electron. I found a nice starter template at GitHub. Unfortunately, with the first update of the packages, there was the problem that some of the packages had switched to pure ESM.
The problem that electron has with ESM is very clear from the issue on GitHub: https://github.com/electron/electron/issues/21457.
Electron use ESM, but not for the files it receives via the config. Electron tries to include these files with "require", which fails. However, a solution is also presented, which can be used well.
Point your eletron toward a cjs file.
In package.json:
"type": "module",
"main": "main.cjs"
In main.cjs:
import('./application.mjs');
After that, to import electron, use this in your esm part:
const require = createRequire(import.meta.url);
const { BrowserWindow, app: electronApp, ipcMain } = require('electron');
But this is only a rough outline of the solution. I forked the starter package and installed the solution there in the ESM branch: https://github.com/studioalex/electron-vue-template/tree/ESM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With