From 639d363a8cbc4b4c765df1f3d4d057b70e511208 Mon Sep 17 00:00:00 2001 From: Haoqun Jiang Date: Wed, 22 Jun 2022 15:33:54 +0800 Subject: [PATCH] fix: support the simple case for `import` external --- packages/vite/src/node/config.ts | 54 ++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index d6ba20fb610d08..df77a9e7b3b379 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -528,6 +528,7 @@ export async function resolveConfig( const middlewareMode = config?.server?.middlewareMode + config = mergeConfig(config, externalConfigCompat(config, configEnv)) const optimizeDeps = config.optimizeDeps || {} const resolved: ResolvedConfig = { @@ -966,3 +967,56 @@ export function isDepsOptimizerEnabled(config: ResolvedConfig): boolean { (command === 'serve' && optimizeDeps.disabled === 'dev') ) } + +// Support `rollupOptions.external` when `legacy.buildRollupPluginCommonjs` is disabled +function externalConfigCompat(config: UserConfig, { command }: ConfigEnv) { + // Only affects the build command + if (command !== 'build') { + return {} + } + + // Skip if using Rollup CommonJS plugin + if ( + config.legacy?.buildRollupPluginCommonjs || + config.optimizeDeps?.disabled === 'build' + ) { + return {} + } + + // Skip if no `external` configured + const external = config?.build?.rollupOptions?.external + if (!external) { + return {} + } + + let normalizedExternal = external + if (typeof external === 'string') { + normalizedExternal = [external] + } + + // TODO: decide whether to support RegExp and function options + // They're not supported yet because `optimizeDeps.exclude` currently only accepts strings + if ( + !Array.isArray(normalizedExternal) || + normalizedExternal.some((ext) => typeof ext !== 'string') + ) { + throw new Error( + `[vite] 'build.rollupOptions.external' can only be an array of strings or a string.\n` + + `You can turn on 'legacy.buildRollupPluginCommonjs' to support more advanced options.` + ) + } + + const additionalConfig: UserConfig = { + optimizeDeps: { + exclude: normalizedExternal as string[], + esbuildOptions: { + plugins: [ + // TODO: configure `optimizeDeps.esbuildOptions.plugins` + // TODO: maybe it can be added unconditionally? + ] + } + } + } + + return additionalConfig +}