From 9c1be108bfb1eac3dbbe432214349153d8b9ed5e Mon Sep 17 00:00:00 2001 From: musicq Date: Tue, 6 Sep 2022 05:06:18 +0800 Subject: [PATCH] refactor: config hook helper function (#9982) --- packages/vite/src/node/config.ts | 43 +++++++++++++++++--------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index 4fb0fcc9a15a93..829c47fee07abf 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -442,16 +442,7 @@ export async function resolveConfig( // run config hooks const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins] - for (const p of getSortedPluginsByHook('config', userPlugins)) { - const hook = p.config - const handler = hook && 'handler' in hook ? hook.handler : hook - if (handler) { - const res = await handler(config, configEnv) - if (res) { - config = mergeConfig(config, res) - } - } - } + config = await runConfigHook(config, userPlugins, configEnv) if (process.env.VITE_TEST_WITHOUT_PLUGIN_COMMONJS) { config = mergeConfig(config, { @@ -611,16 +602,7 @@ export async function resolveConfig( ...workerNormalPlugins, ...workerPostPlugins ] - for (const p of getSortedPluginsByHook('config', workerUserPlugins)) { - const hook = p.config - const handler = hook && 'handler' in hook ? hook.handler : hook - if (handler) { - const res = await handler(workerConfig, configEnv) - if (res) { - workerConfig = mergeConfig(workerConfig, res) - } - } - } + workerConfig = await runConfigHook(workerConfig, workerUserPlugins, configEnv) const resolvedWorkerOptions: ResolveWorkerOptions = { format: workerConfig.worker?.format || 'iife', plugins: [], @@ -1089,6 +1071,27 @@ async function loadConfigFromBundledFile( } } +async function runConfigHook( + config: InlineConfig, + plugins: Plugin[], + configEnv: ConfigEnv +): Promise { + let conf = config + + for (const p of getSortedPluginsByHook('config', plugins)) { + const hook = p.config + const handler = hook && 'handler' in hook ? hook.handler : hook + if (handler) { + const res = await handler(conf, configEnv) + if (res) { + conf = mergeConfig(conf, res) + } + } + } + + return conf +} + export function getDepOptimizationConfig( config: ResolvedConfig, ssr: boolean