nuxt-electron: require is not defined in ES module scope
when run nuxt dev && electron .
error
require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a ‘.js’ file extension and ‘[path]\package.json’ contains “type”: “module”. To treat it as a CommonJS script, rename it to use the ‘.cjs’ file extension.
help me,please!
About this issue
- Original URL
- State: closed
- Created 5 months ago
- Comments: 35 (1 by maintainers)
package.json
Hey! Thanks for the feedback. Will try your solution.
If we’re trying to use ES Modules (ESM) in Electron we should have
"type": "module"in ourpackage.jsonand the preload scripts must have the .mjs extensionThe problem is that the
nuxt-electronplugin does’t do this automatically despite it usingvite-plugin-electroninternally and this was discussed/fixed on electron-vite/vite-plugin-electron#186This is a little
workaroundthat worked for menuxt.config.tsThis generates the proper
dist-electron/preload.mjsfile that the main electron script expects.electron/main.tsI’ve to mention that I don’t know what I’m doing, nor am I a
NuxtorElectronexpert, but all the @angelhdzmultimedia messages helped me to find a way, thanks 🙋♂️.This worked! Thanks for the help.
SOLUTION
In
~/electron/main.ts, replaceprocess.env.ROOT = path.join(process.cwd(), '..')orprocess.env.ROOT = path.join(__dirname, '..')withprocess.env.ROOT = path.join(import.meta.url, '..').As per the error shown,
__dirnamedoesn’t work in ES6 modules. Replacement for modules isimport.meta.urlto get the path to theelectron/main.tsfile (to itself) and from there, 2 levels up to reach the CWD (Current Working Directory, the root of the nuxt project).Tried all the suggestions here but still getting this:
Thanks!!
Not yet. Will keep playing with the
rendereroptions until I solve it and will let you know.Stay tuned to https://github.com/electron-vite/vite-plugin-electron/issues/186
Update
I’m getting somewhere… 👀
Thanks for your help again!I wrote the code in nuxt-electron(https://nuxt.com/modules/electron)
No require is used in the code node:v20.11.0 “@nuxt/ui”: “^2.13.0”, “nuxt”: “^3.10.0”, “vue”: “^3.4.15”, “vue-router”: “^4.2.5” “electron-builder”: “^24.9.1”, “electron”: “^28.2.1”, “nuxt-electron”: “^0.7.0”, “vite-plugin-electron”: “^0.15.6”, “vite-plugin-electron-renderer”: “^0.14.5” PC OS:win 10
Thanks for your help! but ,Still the same error