Skip to content

Commit

Permalink
feat: external built-in modules plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
caoxiemeihao committed Nov 22, 2022
1 parent 57a2a19 commit a5cfc5c
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
5 changes: 5 additions & 0 deletions packages/plugin/vite/src/VitePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -116,6 +117,7 @@ export default class VitePlugin extends PluginBase<VitePluginConfig> {
outDir: path.join(this.baseDir, 'main'),
},
define: (await this.configGenerator).getDefines(),
plugins: [externalBuiltins()],
});

if (watch) {
Expand Down Expand Up @@ -157,6 +159,7 @@ export default class VitePlugin extends PluginBase<VitePluginConfig> {
watch: watch ? {} : null,
outDir: path.join(this.baseDir, 'renderer', entry.name),
},
plugins: [externalBuiltins()],
});

if (watch) {
Expand Down Expand Up @@ -210,3 +213,5 @@ export default class VitePlugin extends PluginBase<VitePluginConfig> {
if (options.exit) process.exit();
};
}

export { VitePlugin };
38 changes: 38 additions & 0 deletions packages/plugin/vite/src/util/plugins.ts
Original file line number Diff line number Diff line change
@@ -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 <Plugin>{
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;
},
};
}

0 comments on commit a5cfc5c

Please sign in to comment.