Skip to content

Vite Plugin with ESM support for main #3439

Closed

Description

@joezappie

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

  1. yarn create electron-app test-esm-vite --template=vite
  2. Add "type": "module", to package.json
  3. Change forge.config.js to export default
  4. Change the header of src/index.js to:
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));
  1. Add an esm squirrel event handler that works with import: ./squirrel.js
  2. Change vite.*.config.mjs to vite.*.config.js
  3. Update forge.config.js paths for plugin-vite to 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

  1. joezappie commented on Dec 12, 2023

    @joezappie
    Author

    I found that I can override that setting in vite.main.config.js:

    // https://vitejs.dev/config
    export default defineConfig({
      resolve: {
        ...
      },
      build: {
        lib: {
          formats: ["es"],
        },
      },
    });
    

    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:

    const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
    ...
    mainWindow.loadFile(path.join(dirname, "index.html"));
    

    However, Vite replaces import.meta.url with self.location and then Vite errors out ReferenceError: 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_ENTRY and MAIN_WINDOW_VITE_ENTRY will need to be generated outside of Vite similar to how the webpack plugin works?

  2. sparecycles commented on Jan 7, 2024

    @sparecycles

    +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-svelte which 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.json in with { "type": "commonjs" } as a work-around but it feels a bit horrid. 😉

  3. Sahasrara commented on Jan 12, 2024

    @Sahasrara

    The combination of svelte + vite + electron + forge doesn't seem to work unless we have ESM support.

  4. caoxiemeihao commented on Jan 12, 2024

    @caoxiemeihao
    Member

    The combination of svelte + vite + electron + forge doesn't seem to work unless we have ESM support.

    You can try to this 👉 #3309

    The next version of Vite plugin will be use "type"="module" by default, coming soon...

  5. Sahasrara commented on Jan 16, 2024

    @Sahasrara

    Is this something that's planned? I'm hoping to use Forge with Svelte + Vite (not SvelteKit).

  6. sparecycles commented on Jan 18, 2024

    @sparecycles

    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.

  7. joezappie commented on Jan 18, 2024

    @joezappie
    Author

    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!

  8. linked a pull request that will close this issuefeat(plugin-vite): upgrade to vite@5 #3468on Feb 3, 2024
  9. caoxiemeihao commented on Feb 9, 2024

    @caoxiemeihao
    Member

    Fixed by #3468

  10. adidahiya commented on Feb 12, 2024

    @adidahiya

    thanks @caoxiemeihao! any ideas when #3468 might land in a release?

  11. jerrygreen commented on Feb 13, 2024

    @jerrygreen

    Wait so I will be able to actually use "type": "module" in my package.json? I need that, too.

    Kinda want to use with SvelteKit, – but it only supports esm projects.

  12. joezappie commented on Feb 25, 2024

    @joezappie
    Author

    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?

  13. joezappie commented on Mar 23, 2024

    @joezappie
    Author

    @caoxiemeihao sorry to ping you, but just curious where this issue stands?

  14. GitMurf commented on Apr 19, 2024

    @GitMurf

    Any update here? I cannot get esm / type: module to work with forge / vite / typescript.

  15. sparecycles commented on Apr 21, 2024

    @sparecycles

    Strange that this issue is closed, as it appears @caoxiemeihao is still working on it: #3572

  16. caoxiemeihao commented on Apr 22, 2024

    @caoxiemeihao
    Member

    Strange that this issue is closed, as it appears @caoxiemeihao is still working on it: #3572

    v7.3.0 can be implemented through user modification to support ESModule, which is not constrained by @electron-forge/plugin-vite.

    #3572 is just making some changes to the template, not a major upgrade.

  17. sparecycles commented on Apr 22, 2024

    @sparecycles

    @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 of vite.base.config.ts methods 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)

  18. caoxiemeihao commented on Apr 26, 2024

    @caoxiemeihao
    Member

    @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 the esm, must be make some changes.

    - const { app } = reuiqire('electroon');
    + import { app } from 'electron';
  19. progmars commented on Nov 24, 2024

    @progmars

    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 require and failed to run it because of package type=module.

    While building, vite generates a warning

    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.
    

    and with VITE_CJS_TRACE=true I see that it comes from node_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 run npm start anymore:

    'electron-forge' is not recognized as an internal or external command,
    operable program or batch file.
    

    I guess, something differs a lot in main or I don't know how to install main branch in node_modules properly.

  20. matsilva commented on Mar 6, 2025

    @matsilva

    Here are a few things I had to tweak to get pure esm to work for me.

    1. Package.json Configuration

      {
        "type": "module",
        "config": {
          "forge": "./forge.config.mjs"
        }
      }
      • Set "type": "module" to make all .js files use ESM by default
      • Configure Electron Forge to use the .mjs config file
    2. Forge Configuration

      • Renamed forge.config.js to forge.config.mjs for explicit ESM support
      • Used ESM imports and exports:
      import { FusesPlugin } from '@electron-forge/plugin-fuses';
      const config = { /* ... */ };
      export default config;
    3. Vite Configuration

      • Updated build configuration to use ESM format:
      // vite.main.config.mjs & vite.preload.config.mjs
      export default defineConfig({
        build: {
          lib: {
            formats: ['es'],
            // ...
          }
        }
      });
    4. Main Process Code (main.js)

      • Replaced CommonJS __dirname with ESM equivalent:
      import { fileURLToPath } from 'node:url';
      import { dirname, join } from 'node:path';
      
      const __filename = fileURLToPath(import.meta.url);
      const __dirname = dirname(__filename);
      • Used join instead of path.join
      • Used proper ESM imports with file extensions where needed
    5. Import Statements

      • Used proper ESM import syntax throughout:
      import { app } from 'electron';
      import { dirname } from 'node:path';

      Instead of CommonJS:

      const { app } = require('electron');
      const { dirname } = require('path');

    The most critical part was handling the __dirname replacement, as this is one of the main differences between CommonJS and ESM in Node.js environments. In ESM, global variables like __dirname and __filename don't exist, so you have to construct them using import.meta.url.

  21. LucasMatuszewski commented on Mar 28, 2025

    @LucasMatuszewski

    Thanks a lot @matsilva - it worked for me, I can build / make without errors on require() in main.mjs output file.

    But I still get the same deprecation error on pugin-vite using vite/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.js I don't see any mjs dist files, only .js files with CommonJS inside, using require() like const 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:

    commonjsOptions: {
          // Transform require() calls to imports in mixed ESM/CommonJS modules
          transformMixedEsModules: true,
        },
    
  22. GitMurf commented on Mar 28, 2025

    @GitMurf

    @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.

  23. Skarvion commented on Jun 20, 2025

    @Skarvion

    Hi @matsilva ,

    In step 3, you've added the { lib: { formats: ["es"] } } configuration. But when I tried, it throws an error as now it requires entry as mandatory. But if I provided it, it will combine both main and preload file 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.

  24. erickzhao commented on Jun 20, 2025

    @erickzhao
    Member

    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.

    This is stemming from the fact that Forge's internal tsconfig.json still 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

  25. abencun-symphony commented on Aug 18, 2025

    @abencun-symphony

    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

    "type": "module"

    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

    import { defineConfig } from 'vite';
    
    export default defineConfig({
      build: {
        lib: {
          formats: ['cjs'],
          entry: './src/preload.ts',
          fileName: 'preload',
        },
      },
    });

    vite.main.config.ts

    import { defineConfig } from 'vite';
    
    export default defineConfig({
      build: {
        lib: {
          formats: ['es'],
          entry: './src/main.ts',
          fileName: 'main',
        },
      },
    });

    vite.renderer.config.ts

    /* eslint-disable import/no-unresolved */
    
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    import tailwind from '@tailwindcss/vite';
    
    export default defineConfig({
      plugins: [react(), tailwind()],
    });

    And I also had to "polyfill" the __dirname and __filename in my main.ts:

    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);

    Also, rename renderer.ts to renderer.tsx.

    Then, in index.html:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
        <title>Hello World!</title>
    
      </head>
      <body>
        <div id="root"></div>
        <script type="module" src="/src/renderer.tsx"></script>
      </body>
    </html>
  26. Sanan4li commented on Jan 8, 2026

    @Sanan4li

    @tailwindcss/vite

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions