diff --git a/packages/plugin/vite/src/VitePlugin.ts b/packages/plugin/vite/src/VitePlugin.ts index 4290a697f8..39e83b197d 100644 --- a/packages/plugin/vite/src/VitePlugin.ts +++ b/packages/plugin/vite/src/VitePlugin.ts @@ -10,6 +10,7 @@ import { RollupWatcher } from 'rollup'; import { default as vite } from 'vite'; import { VitePluginConfig } from './Config'; +import { externalBuiltins } from './util/plugins'; import ViteConfigGenerator from './ViteConfig'; const d = debug('electron-forge:plugin:vite'); @@ -116,6 +117,7 @@ export default class VitePlugin extends PluginBase { outDir: path.join(this.baseDir, 'main'), }, define: (await this.configGenerator).getDefines(), + plugins: [externalBuiltins()], }); if (watch) { @@ -157,6 +159,7 @@ export default class VitePlugin extends PluginBase { watch: watch ? {} : null, outDir: path.join(this.baseDir, 'renderer', entry.name), }, + plugins: [externalBuiltins()], }); if (watch) { @@ -210,3 +213,5 @@ export default class VitePlugin extends PluginBase { if (options.exit) process.exit(); }; } + +export { VitePlugin }; diff --git a/packages/plugin/vite/src/util/plugins.ts b/packages/plugin/vite/src/util/plugins.ts new file mode 100644 index 0000000000..5ae710369d --- /dev/null +++ b/packages/plugin/vite/src/util/plugins.ts @@ -0,0 +1,38 @@ +import { builtinModules } from 'node:module'; + +import type { Plugin } from 'vite'; + +/** + * `electron` and Node.js built-in modules should always be externalize. + */ +export function externalBuiltins() { + return { + name: '@electron-forge/plugin-vite:external-builtins', + config(config) { + const builtins = [ + 'electron', + ...builtinModules.filter((e) => !e.startsWith('_')), + ...builtinModules.filter((e) => !e.startsWith('_')).map((m) => `node:${m}`), + ]; + + config.build ??= {}; + config.build.rollupOptions ??= {}; + + let external = config.build.rollupOptions.external; + if (Array.isArray(external) || typeof external === 'string' || external instanceof RegExp) { + external = builtins.concat(external as string[]); + } else if (typeof external === 'function') { + const original = external; + external = function (source, importer, isResolved) { + if (builtins.includes(source)) { + return true; + } + return original(source, importer, isResolved); + }; + } else { + external = builtins; + } + config.build.rollupOptions.external = external; + }, + }; +}