Skip to content

Forge make combined with vite is creating an incomplete asar #3738

Open

Description

@steveoh

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

Electron version

33.0.1

Operating system

windows 11

Last known working Electron Forge version

7.4.0

Expected behavior

npm run make creates an asar file that includes the node_modules and the app can run on windows successfully.

Actual behavior

node_modules aren't present and install fails with ERR_MODULE_NOT_FOUND

Steps to reproduce

  1. npm run make
  2. go to the out folder and find open the nupkg/resources/app.asar file
  3. run npx @electron/asar extract app.asar app
  4. notice there is no node_modules

Additional information

This is only happening on windows as I believe that is the only place that asar is used.
We are using vite instead of webpack.

Image

The main.js file from within the asar in the error message imports the following

import "node:path";
import "node:url";
import "electron";
import "electron-window-state";
import "update-electron-app";
import "./main-DWMHPuxT.js";
import "electron-squirrel-startup";
import "fs";
import "path";
import "url";
import "stream";
import "zlib";

Where electron-window-state and update-electron-app and I assume electron-squirrel-startup are not available to be imported.

Activity

  1. justgo97 commented on Oct 17, 2024

    @justgo97

    I'm not sure about 7.5.0 but in earlier versions it was needed to move electron-window-state and any other dependency that isn't getting bundled correctly to devDependencies in package.json, This is a known mismatch between vite and webpack in forge.

  2. steveoh commented on Oct 17, 2024

    @steveoh
    Author

    This works as expected downgrading to 7.4.0. I'll give this a try but no bundles are getting added to the app.asar file at 7.5.0.

    Well now I'm getting a require is not defined error after making the project. :/

  3. s1mple-007 commented on Oct 22, 2024

    @s1mple-007

    @steveoh I use electron-log and it works fine after downgrading.

  4. knice88 commented on Oct 29, 2024

    @knice88

    I've had this happen to ubuntu as well, but found a way to get the trick:
    When you run "npm run make" for the first time, open the @electron-forge/plugin-vite configuration, get the .vite/ folder, and delete the out/ folder; Then turn off the @electron-forge/plugin-vite config and run "npm run make" again to get a complete installer

  5. AimForNaN commented on Oct 30, 2024

    @AimForNaN

    Ran into a similar issue with other packages. Found a work-around and modified it to work for me. Seems @electron/packager related.

    // forge.config.js
    
    const { spawn } = require('node:child_process');
    
    module.exports = {
    	hooks: {
    		packageAfterPrune: async (config, build_path) => {
    			const vite_config = await import('./vite.preload.config.mjs');
    			const external = vite_config?.default?.build?.rollupOptions?.external || [];
    			const commands = [
    				'install',
    				'--no-package-lock',
    				'--no-save',
    				...external,
    			];
    
    			return new Promise((resolve, reject) => {
    				npm = spawn('npm', commands, {
    					cwd: build_path,
    					stdio: 'inherit',
    					shell: true,
    				});
    
    				npm.on('close', (code) => {
    					if (0 === code) {
    						resolve();
    						return;
    					}
    
    					reject(`Process exited with code: ${code}`);
    				});
    
    				npm.on('error', reject);
    			});
    		},
    	},
    	// ...
    };
  6. clicktodev commented on Nov 3, 2024

    @clicktodev

    same issue here, happens when trying to load a json file

    const filePath = path.join(__dirname, "schedule.json");
    const data = fs.readFileSync(filePath , "utf-8");
    
  7. clicktodev commented on Nov 3, 2024

    @clicktodev

    temp workaround is to disable asar by modifying the following properties in forge.config.ts

    const config: ForgeConfig = {
      packagerConfig: {
        asar: false,
      },
      plugins: [
        new FusesPlugin({
          [FuseV1Options.OnlyLoadAppFromAsar]: false,
        }),
      ],
    };
  8. anjimkofy commented on Nov 20, 2024

    @anjimkofy

    This error is not related to ASAR. Even if ASAR is disabled, the error is still reported. I think it is a vite plug-in problem. It works normally in 7.4.0

  9. DrShortStack commented on Dec 5, 2024

    @DrShortStack

    I'm getting this issue on 7.4.0, I can't find any errors in the logs to understand what's causing it.

  10. GitMurf commented on Jan 17, 2025

    @GitMurf

    Still having these same problems with forge 7.6. The docs state (see screenshot below) that native node modules should work "out of the box", which they do not. But also trying any of the "workarounds" is not working either... added to build.rollupOptions.external etc. and still not getting any node_modules included in the package.

    This is starting to become very frustrating. Last year spent months figuring out workarounds to make 7.3/7.4 work with vite to properly package the correct node modules... finally got it working, but now to update to the current stable version of electron (v34) need to update forge as well and now everything is broken again with native modules.

    Image

    I hate to make a negative post but this is becoming a pattern and a real issue any time we have to consider updating anything with electron forge (for vite). cc @erickzhao

  11. lorenzjosten commented on Jan 19, 2025

    @lorenzjosten

    I would like to know if I am also affected by the issue at hand. - So that I can put my mind to rest, after having put in far too many hours to get the release build of my project to run with better-sqlite3 marked as an external lib. I have scrolled through docs, forums and bug reports looking for a solution. But I am still stuck.

    I am using a MacBook (arm64 with M2 chip). I have setup my project with

    create-electron-app . --template=vite-typescript

    After running the electron forge package command

    yarn run package

    and starting the bundled app

    open out/test-darwin-arm64/test.app  

    I am running into this error:

    Image
    package.json
    {
      "name": "test",
      "productName": "test",
      "version": "1.0.0",
      "description": "My Electron application description",
      "main": ".vite/build/main.js",
      "scripts": {
        "start": "electron-forge start",
        "package": "electron-forge package",
        "make": "electron-forge make",
        "publish": "electron-forge publish"
      },
      "devDependencies": {
        "@electron-forge/cli": "^7.6.0",
        "@electron-forge/maker-deb": "^7.6.0",
        "@electron-forge/maker-rpm": "^7.6.0",
        "@electron-forge/maker-squirrel": "^7.6.0",
        "@electron-forge/maker-zip": "^7.6.0",
        "@electron-forge/plugin-auto-unpack-natives": "^7.6.0",
        "@electron-forge/plugin-fuses": "^7.6.0",
        "@electron-forge/plugin-vite": "^7.6.0",
        "@electron/asar": "^3.2.18",
        "@electron/fuses": "^1.8.0",
        "@types/bootstrap": "^5",
        "@types/electron-squirrel-startup": "^1",
        "@types/node": "^22.10.5",
        "@vitejs/plugin-vue": "^5.2.1",
        "electron": "33.3.1",
        "ts-node": "^10.9.2",
        "typescript": "^5.7.2",
        "vite": "^5.0.12",
        "vue": "^3.5.13",
        "vue-tsc": "^2.2.0"
      },
      "keywords": [],
      "author": {
        "name": "***",
        "email": "***"
      },
      "license": "MIT",
      "packageManager": "[email protected]+sha512.5383cc12567a95f1d668fbe762dfe0075c595b4bfff433be478dbbe24e05251a8e8c3eb992a986667c1d53b6c3a9c85b8398c35a960587fbd9fa3a0915406728",
      "dependencies": {
        "@popperjs/core": "^2.11.8",
        "@types/better-sqlite3": "^7.6.12",
        "apexcharts": "^4.3.0",
        "axios": "^1.7.9",
        "better-sqlite3": "^11.8.1",
        "bootstrap": "^5.3.3",
        "bootstrap-icons": "^1.11.3",
        "electron-squirrel-startup": "^1.0.1",
        "pinia": "^2.3.0",
        "vue-router": "^4.5.0",
        "vue3-apexcharts": "^1.8.0"
      }
    }
    vite.main.config.ts
    import path from 'path';
    import { defineConfig } from 'vite';
    
    // https://vitejs.dev/config
    export default defineConfig({
        resolve: {
            alias: {
                '@': path.resolve(__dirname, './src')
            }
        },
        build: {
            rollupOptions: {
                external: [
                    'better-sqlite3'
                ],
            },
        }
    });
    forge.config.ts
    import type { ForgeConfig } from '@electron-forge/shared-types';
    import { AutoUnpackNativesPlugin } from '@electron-forge/plugin-auto-unpack-natives';
    import { MakerSquirrel } from '@electron-forge/maker-squirrel';
    import { MakerZIP } from '@electron-forge/maker-zip';
    import { MakerDeb } from '@electron-forge/maker-deb';
    import { MakerRpm } from '@electron-forge/maker-rpm';
    import { VitePlugin } from '@electron-forge/plugin-vite';
    import { FusesPlugin } from '@electron-forge/plugin-fuses';
    import { FuseV1Options, FuseVersion } from '@electron/fuses';
    
    const config: ForgeConfig = {
      packagerConfig: {
        asar: {
          unpack: "**/node_modules/better-sqlite3/**/*"
        },
      },
      rebuildConfig: {
        onlyModules: ['better-sqlite3'],
        buildFromSource: true,
        force: true,
      },
      makers: [new MakerSquirrel({}), new MakerZIP({}, ['darwin']), new MakerRpm({}), new MakerDeb({})],
      plugins: [
        new AutoUnpackNativesPlugin({}),
        new VitePlugin({
          // `build` can specify multiple entry builds, which can be Main process, Preload scripts, Worker process, etc.
          // If you are familiar with Vite configuration, it will look really familiar.
          build: [
            {
              // `entry` is just an alias for `build.lib.entry` in the corresponding file of `config`.
              entry: 'src/main.ts',
              config: 'vite.main.config.ts',
              target: 'main',
            },
            {
              entry: 'src/preload.ts',
              config: 'vite.preload.config.ts',
              target: 'preload',
            },
          ],
          renderer: [
            {
              name: 'main_window',
              config: 'vite.renderer.config.ts',
            },
          ],
        }),
        // Fuses are used to enable/disable various Electron functionality
        // at package time, before code signing the application
        new FusesPlugin({
          version: FuseVersion.V1,
          [FuseV1Options.RunAsNode]: false,
          [FuseV1Options.EnableCookieEncryption]: true,
          [FuseV1Options.EnableNodeOptionsEnvironmentVariable]: false,
          [FuseV1Options.EnableNodeCliInspectArguments]: false,
          [FuseV1Options.EnableEmbeddedAsarIntegrityValidation]: true,
          [FuseV1Options.OnlyLoadAppFromAsar]: true,
        }),
      ],
    };
    
    export default config;

    Note that leaving out the AutoUnpackNatviesPlugin or the rebuildConfig does not change the behaviour. Cheers!

  12. clicktodev commented on Jan 19, 2025

    @clicktodev

    temp workaround is to disable asar by modifying the following properties in forge.config.ts

    const config: ForgeConfig = {
    packagerConfig: {
    asar: false,
    },
    plugins: [
    new FusesPlugin({
    [FuseV1Options.OnlyLoadAppFromAsar]: false,
    }),
    ],
    };

    again for anyone willing to forgo asar, disabling it fixed everything in my case

  13. GitMurf commented on Jan 20, 2025

    @GitMurf

    @lorenzjosten yes the problem is the vite plugin for forge is not packaging any node_modules which means if you use any node native libs like better-sqlite it will not work.

    It will work in dev because forge/vite uses the external package config option to know to leverage your local node_modules for those native libs like better-SQLite. But then when packaged for production those required node_modules are missing so everything breaks.

  14. edymusajev commented on Jan 20, 2025

    @edymusajev
  15. 41 remaining items

  16. wz2cool commented on Oct 2, 2025

    @wz2cool
    import { MakerDeb } from '@electron-forge/maker-deb'
    import { MakerZIP } from '@electron-forge/maker-zip'
    import { AutoUnpackNativesPlugin } from '@electron-forge/plugin-auto-unpack-natives'   // <--- add this
    import { FusesPlugin } from '@electron-forge/plugin-fuses'
    import { VitePlugin } from '@electron-forge/plugin-vite'
    import type { ForgeConfig } from '@electron-forge/shared-types'
    
    import { FuseV1Options, FuseVersion } from '@electron/fuses'
    
    const config: ForgeConfig = {
      packagerConfig: { asar: true, ignore: [] }, // <--- add this ignore and leave it empty
      rebuildConfig: {},
      // makers: [new MakerSquirrel({}), new MakerZIP({}, ['darwin']), new MakerRpm({}), new MakerDeb({})],
      makers: [new MakerDeb({}), new MakerZIP({}, ['darwin'])],
      plugins: [
        new AutoUnpackNativesPlugin({}), // <--- add this
    
    ...
    

    save my day , thank you so much

  17. knotekbr commented on Oct 5, 2025

    @knotekbr

    Unfortunately, the solution @GitMurf posted didn't work for me. However, I was able to combine it with another solution posted by Dan Corin. As has been mentioned elsewhere, YMMV. Also I'm pretty new to Electron, so I may be overlooking something.

    My only additions to the default forge config were a packageAfterCopy hook and the AutoUnpackNativesPlugin plugin, which seem to have solved the problem for me:

    import fsp from "node:fs/promises";
    import path from "node:path";
    
    import { AutoUnpackNativesPlugin } from "@electron-forge/plugin-auto-unpack-natives";
    import { FusesPlugin } from "@electron-forge/plugin-fuses";
    import { VitePlugin } from "@electron-forge/plugin-vite";
    import { Walker, DepType } from "flora-colossus";
    
    import type { ForgeConfig } from "@electron-forge/shared-types";
    import type { Module } from "flora-colossus";
    
    type CopyClass<T> = {
      [P in keyof T]: T[P];
    };
    
    type CustomWalker = CopyClass<Walker> & {
      modules: Module[];
      walkDependenciesForModule: (moduleRoot: string, depType: DepType) => Promise<void>;
    };
    
    const externalDependencies = ["velopack"];
    
    const config: ForgeConfig = {
      packagerConfig: {
        asar: true,
      },
      hooks: {
        async packageAfterCopy(_forgeConfig, buildPath) {
          const depsToCopy = new Set<string>(externalDependencies);
    
          const sourceNodeModulesPath = path.resolve(__dirname, "node_modules");
          const destNodeModulesPath = path.resolve(buildPath, "node_modules");
    
          for (const dep of externalDependencies) {
            const walker = new Walker(path.join(sourceNodeModulesPath, dep)) as unknown as CustomWalker;
    
            await walker.walkDependenciesForModule(path.join(sourceNodeModulesPath, dep), DepType.PROD);
    
            walker.modules.forEach((treeDep) => {
              depsToCopy.add(treeDep.name);
            });
          }
    
          await Promise.all(
            Array.from(depsToCopy.values()).map(async (packageName) => {
              const sourcePath = path.join(sourceNodeModulesPath, packageName);
              const destPath = path.join(destNodeModulesPath, packageName);
    
              await fsp.mkdir(path.dirname(destPath), { recursive: true });
              await fsp.cp(sourcePath, destPath, { recursive: true, preserveTimestamps: true });
            })
          );
        },
      },
    
      makers: [/* ...makers */],
    
      plugins: [
        new VitePlugin({ /* Vite plugin config */ }),
        new FusesPlugin({ /* Fuses plugin config */ }),
        new AutoUnpackNativesPlugin({}),
      ],
    };
    
    export default config;
  18. ArashYounesi commented on Nov 10, 2025

    @ArashYounesi

    @wangha81 You’re a lifesaver — let me kiss your hand 😘

  19. GeorgeCrisan commented on Jan 11, 2026

    @GeorgeCrisan

    If you are like me and you care about one package only, a simplified version of @knotekbr 's answer

      hooks: {
        async packageAfterCopy(_forgeConfig, buildPath) {
          const sourceNodeModulesPath = path.resolve(__dirname, "node_modules");
          const destNodeModulesPath = path.resolve(buildPath, "node_modules");
    
          const sourcePath = path.join(sourceNodeModulesPath, '@fugood');
          const destPath = path.join(destNodeModulesPath, '@fugood');
    
          await fsp.mkdir(path.dirname(destPath), { recursive: true });
          await fsp.cp(sourcePath, destPath, { recursive: true, preserveTimestamps: true });
    
        },
      },
    
  20. Sergo706 commented on May 22, 2026

    @Sergo706

    @Tomyail Tried many of the solutions here thats the only one that worked. Thanks.

    @electron-forge/cli 7.11.1

  21. jagthedrummer commented on Aug 3, 2026

    @jagthedrummer

    I just ran into this problem and I found that just adding ignore: [] to the forge config did the trick. I didn't need AutoUnpackNativesPlugin or any kind of hook.

    With the ignore config I get this warning in the output:

    You have set packagerConfig.ignore, the Electron Forge Vite plugin normally sets this automatically.
    
    Your packaged app may be larger than expected if you dont ignore everything other than the '.vite' folder
    

    And the resulting .app file is about 30Mb larger than without the ignore. But without the ignore the .app file doesn't work at all, so I'm not too worried about the 30Mb.

  22. lvyanyan commented on Sep 3, 2026

    @lvyanyan

    I dug into this with a v7.4.0...v7.5.0 diff and I believe I can pin the root cause: #3583 (feat(plugin-vite): better logic, commit 83fa9cf) removed the "copy dependencies into the built app" step while the externals semantics of apps created with the pre-7.5 template still assume it.

    The failure chain:

    1. In the pre-7.5 template, vite.main.config.ts externalized everything from package.json dependencies (the deal was: don't bundle, the packager copies them).
    2. feat(plugin-vite): better logic #3583 removed the copy step — correct under the new philosophy, where the default external is just Node builtins + electron (see packages/plugin/vite/src/config/vite.base.config.ts), so pure-JS deps get bundled into main-*.js.
    3. Apps that upgraded from ≤7.4 still carry the old config, so their dependencies are externalized (see the reporter's built main.js: bare import "electron-window-state", import "update-electron-app" next to the bundled ./main-DWMHPuxT.js) — and nobody copies them anymore. Hence ERR_MODULE_NOT_FOUND, on every OS (the asar angle is a red herring: disabling asar doesn't help because the app directory itself has no node_modules).

    This also explains the two widely-quoted workarounds in this thread: moving those deps to devDependencies (drops them from the old external list → vite bundles them), and downgrading to 7.4.0 (the copy step still exists).

    Possible directions, would love a maintainer's take (my recommendation is 1, with 3 alongside):

    1. Fail fast (recommended): at package time, detect dependencies that are externalized but not covered by any node_modules-collection step, and error with actionable text ("move to devDependencies to bundle, or ..."). Smallest change, zero behavior change for correct setups, and it converts every future occurrence of this silent failure into a clear, self-documenting error.
    2. Restore an opt-in copy for externalized deps behind a config flag. I'd be cautious here: teams who want copies already have an escape hatch (packagerConfig.afterCopy), and a second packaging path inside plugin-vite is exactly the kind of surface that produced this regression.
    3. Migration/docs: a note in the vite plugin docs for pre-7.5 apps ("if your vite.*.config.ts externalizes dependencies, remove that — they are bundled now"). Worth doing regardless, but docs alone don't stop the silent failure.

    Happy to work on whichever direction maintainers prefer.

    (Drafted with AI assistance and reviewed by the author.)

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

Metadata

Metadata

Assignees

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions