Repository navigation
Description
Pre-flight checklist
- I have read the contribution documentation for this project.
- I agree to follow the code of conduct that this project uses.
- I have searched the issue tracker for a bug that matches the one I want to file, without success.
Electron Forge version
7.2.0
Electron version
v28.0.0
Operating system
Windows 10 22H2
Last known working Electron Forge version
N/A
Expected behavior
I see that V28 brings ESM support (Hooray!). I'd like to switch my projects over but I'm having issues getting the Vite template to build. I successfully got a normal electron-forge app to build but using the vite template I cannot as it still converts it to cjs.
Actual behavior
Vite converts main.js to cjs, in which it then errors out because the package.json has been updated to include "type": "module".
App threw an error during load
ReferenceError: 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 'C:\Users\joeja\projects\deleteme-vite\pack
age.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///C:/Users/joeja/projects/deleteme-vite/.vite/build/main.js:1:22
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
Steps to reproduce
yarn create electron-app test-esm-vite --template=vite- Add
"type": "module",topackage.json - Change
forge.config.jstoexport default - Change the header of
src/index.jsto:
import { app, BrowserWindow } from "electron";
import path from "path";
import * as url from "url";
import { handleSquirrelEvent } from "./squirrel.js";
const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
- Add an esm squirrel event handler that works with import:
./squirrel.js - Change
vite.*.config.mjstovite.*.config.js - Update
forge.config.jspaths forplugin-viteto remove.mjs
Additional information
Looking through the vite plugin code, there is still a reference stating that Electron doesn't support ESM which is no longer true. Can this be updated?
Line 76 in file: https://github.com/electron/forge/blob/main/packages/plugin/vite/src/ViteConfig.ts
build: {
lib: entry
? {
entry,
// Electron can only support cjs.
formats: ['cjs'],
fileName: () => '[name].js',
}
: undefined,
I tried overriding this in my defineConfig({}) but haven't had any luck:
{
// `entry` is just an alias for `build.lib.entry` in the corresponding file of `config`.
entry: "src/main.js",
formats: ["es"],
config: "vite.main.config.js",
},
I know this is an on going effort to update everything. I'd figure I'd bring it to attention since the code now says something that's untrue and because I can't figure out what the work around to override this.
Activity
joezappie commentedon Dec 12, 2023
I found that I can override that setting in
vite.main.config.js:I have another issue now though, as in esm __dirname is not available. This is needed to specify the index.html path and the preload file. I changed it to:
However, Vite replaces
import.meta.urlwithself.locationand then Vite errors outReferenceError: self is not defined.If I replace them with relative paths, it loads the files but warns it wants an absolute path for preload.js.
Guessing some sort of
MAIN_WINDOW_PRELOAD_VITE_ENTRYandMAIN_WINDOW_VITE_ENTRYwill need to be generated outside of Vite similar to how the webpack plugin works?sparecycles commentedon Jan 7, 2024
+1.
Thanks for your investigation!
I wonder if you tried
import.meta.resolve(...)? It's both more to the point and perhaps vite doesn't try to mess with it?I'm brought here trying to use both
@sveltejs/vite-plugin-sveltewhich is esm-only, (and so it requires"type": "module"in package.json), and this is tripping me up.I think I can slap an
dist-electron/package.jsonin with{ "type": "commonjs" }as a work-around but it feels a bit horrid. 😉Sahasrara commentedon Jan 12, 2024
The combination of svelte + vite + electron + forge doesn't seem to work unless we have ESM support.
caoxiemeihao commentedon Jan 12, 2024
You can try to this 👉 #3309
The next version of Vite plugin will be use
"type"="module"by default, coming soon...Sahasrara commentedon Jan 16, 2024
Is this something that's planned? I'm hoping to use Forge with Svelte + Vite (not SvelteKit).
sparecycles commentedon Jan 18, 2024
The "horrid" workaround I suggested seems to be working for me. I've got
vite+forge+tailwind+typescript+svelte+melt+workers+import("node:module").register(node20, electron29-alpha) working fine.joezappie commentedon Jan 18, 2024
Aweome! I haven't had a chance to try your suggestion but I'm starting a new project tomorrow and might mess around with it more. Hopefully the official support comes soon but good to know its coming by default soon!
caoxiemeihao commentedon Feb 9, 2024
Fixed by #3468
adidahiya commentedon Feb 12, 2024
thanks @caoxiemeihao! any ideas when #3468 might land in a release?
jerrygreen commentedon Feb 13, 2024
Wait so I will be able to actually use
"type": "module"in mypackage.json? I need that, too.Kinda want to use with SvelteKit, – but it only supports esm projects.
joezappie commentedon Feb 25, 2024
Was this supposed to be fixed in the 7.3.0 release? This issue was closed, but even with running a fresh install
npm init electron-app@latest my-new-app -- --template=vite, its still using CJS for main and"type":"module"is not in the package.json.Edit - Hmm yeah, looking through the current code, it doesnt look like theres any changes to the template to use esm and not cjs for main. It still uses mjs files for the config and main.config references
formats: ['cjs'],still. Can this issue be reopened?joezappie commentedon Mar 23, 2024
@caoxiemeihao sorry to ping you, but just curious where this issue stands?
GitMurf commentedon Apr 19, 2024
Any update here? I cannot get esm / type: module to work with forge / vite / typescript.
sparecycles commentedon Apr 21, 2024
Strange that this issue is closed, as it appears @caoxiemeihao is still working on it: #3572
caoxiemeihao commentedon Apr 22, 2024
v7.3.0can be implemented through user modification to supportESModule, which is not constrained by@electron-forge/plugin-vite.#3572 is just making some changes to the template, not a major upgrade.
sparecycles commentedon Apr 22, 2024
@caoxiemeihao yep, I confirmed this today via these application-side changes
https://github.com/sparecycles/vite-svelte-tailwind-electron/compare/forge-7.3.0..forge-7.3.0-esm and then
https://github.com/sparecycles/vite-svelte-tailwind-electron/compare/forge-7.3.0-rewrite..forge-7.3.0-rewrite-esm-support
@joezappie
I think it's worth trying to apply the
extendMainConfig({...}),extendPreloadConfig({...}),extendRendererConfig({...})from my rewrite ofvite.base.config.tsmethods to existing templates to see if it "just works", (but I don't intend to support this long-term, nor do I have the resources to debug on a wide variety of platforms at the moment.)See #3506 (comment)
(EDIT: preload.ts might need to be cjs still... broken)
caoxiemeihao commentedon Apr 26, 2024
@sparecycles You gave me some inspiration and I updated the API design for migration to
7.3.0+.BTW, It can support
{ "type": "module" }. But if you want use theesm, must be make some changes.progmars commentedon Nov 24, 2024
This is still confusing. In the main branch vite template, there still seems to be a mix with mjs and
require; no pure js and type=module.I tried to modify it all manually based on the template, but vite still ended up generating main.js file with
requireand failed to run it because of package type=module.While building, vite generates a warning
and with
VITE_CJS_TRACE=trueI see that it comes fromnode_modules\vite\index.cjs. Why is Electron Forge still triggering cjs and not ESM Vite process?What is the best way to create ESM-enabled vite project (without Typescript)?
Tried to update devDependencies to
electron/forge#main, it required ts-node, which I installed, but then I could not runnpm startanymore:I guess, something differs a lot in main or I don't know how to install main branch in node_modules properly.
matsilva commentedon Mar 6, 2025
Here are a few things I had to tweak to get pure esm to work for me.
Package.json Configuration
{ "type": "module", "config": { "forge": "./forge.config.mjs" } }"type": "module"to make all.jsfiles use ESM by default.mjsconfig fileForge Configuration
forge.config.jstoforge.config.mjsfor explicit ESM supportVite Configuration
Main Process Code (main.js)
__dirnamewith ESM equivalent:joininstead ofpath.joinImport Statements
Instead of CommonJS:
The most critical part was handling the
__dirnamereplacement, as this is one of the main differences between CommonJS and ESM in Node.js environments. In ESM, global variables like__dirnameand__filenamedon't exist, so you have to construct them usingimport.meta.url.LucasMatuszewski commentedon Mar 28, 2025
Thanks a lot @matsilva - it worked for me, I can build / make without errors on
require()inmain.mjsoutput file.But I still get the same deprecation error on
pugin-viteusingvite/index.cjs:The CJS build of Vite's Node API is deprecated. See https://vite.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.In
node_modules/@electron-forge/plugin-vite/dist/VitePlugin.jsI don't see any mjs dist files, only .js files with CommonJS inside, usingrequire()likeconst vite_1 = __importDefault(require("vite"));- so it looks like the Plugin is still in CJS only? (I have v7.8.0)Do you also have it, or did you manage to get rid of it?
I tried this build setting, but it didn't help:
GitMurf commentedon Mar 28, 2025
@LucasMatuszewski i have never figured out a way to resolve that deprecation warning either! It may be a good one to open a new issue on because I'm not sure if the electron forge team is aware of this.
Skarvion commentedon Jun 20, 2025
Hi @matsilva ,
In step 3, you've added the
{ lib: { formats: ["es"] } }configuration. But when I tried, it throws an error as now it requiresentryas mandatory. But if I provided it, it will combine bothmainandpreloadfile to a single file.Is that to be expected? Is there any changes needed in
forge.config.mts? Please show the full config file for vite and forge.erickzhao commentedon Jun 20, 2025
This is stemming from the fact that Forge's internal
tsconfig.jsonstill uses CommonJS module resolution. To silence this warning, there's an environment variable you can set (will be added by default to the next version of Forge):8019359#diff-d1d8524b16d69b5d383151b395f4ac4151282b39dac16af4bd833cae8b689c8cR2
abencun-symphony commentedon Aug 18, 2025
I had issues with the latest Electron Forge Vite template trying to add React and Tailwind to it and I did something similar to what @matsilva did but I have also split up the tsconfig into multiple files and do some other stuff as well:
package.json
tsconfig.json
{ "files": [], "references": [{ "path": "./tsconfig.node.json" }, { "path": "./tsconfig.renderer.json" }] }tsconfig.node.json
{ "extends": "./tsconfig.json", "compilerOptions": { "module": "esnext", "moduleResolution": "bundler", "target": "esnext", "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "noImplicitAny": true, "sourceMap": true, "baseUrl": ".", "outDir": "dist", "resolveJsonModule": true }, "include": [ "vite.main.config.ts", "vite.preload.config.ts", "forge.config.ts", "src/main.ts", "src/preload.ts", "*.d.ts" ] }tsconfig.renderer.json
{ "extends": "./tsconfig.json", "compilerOptions": { "module": "esnext", "moduleResolution": "bundler", "target": "esnext", "jsx": "react-jsx", "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "noImplicitAny": true, "sourceMap": true, "baseUrl": ".", "outDir": "dist", "resolveJsonModule": true }, "include": ["src/renderer.tsx", "vite.renderer.config.ts", "*.d.ts"] }vite.preload.config.ts
vite.main.config.ts
vite.renderer.config.ts
And I also had to "polyfill" the
__dirnameand__filenamein mymain.ts:Also, rename
renderer.tstorenderer.tsx.Then, in
index.html:Sanan4li commentedon Jan 8, 2026
I had hard time in installing tailwindcss with react + vite. This really helped. I would suggest to add these steps in the official docs with "Installing TailwindCSS" section.