|
| 1 | +import type { Plugin, ResolvedConfig, ViteBuilder } from 'vite' |
| 2 | +import type { ResolvedDevToolsConfig } from '../config' |
| 3 | + |
| 4 | +type DevToolsEnvironment = ResolvedConfig['environments'][string] |
| 5 | + |
| 6 | +export interface DevToolsIntegrationOptions { |
| 7 | + config: ResolvedConfig |
| 8 | +} |
| 9 | + |
| 10 | +function getDevToolsEnvironments(config: ResolvedConfig): DevToolsEnvironment[] { |
| 11 | + const devToolsConfig = config.devtools as ResolvedDevToolsConfig |
| 12 | + const environmentNames = devToolsConfig.config.environments ?? Object.keys(config.environments) |
| 13 | + const environments: DevToolsEnvironment[] = [] |
| 14 | + |
| 15 | + for (const environmentName of environmentNames) { |
| 16 | + const environment = config.environments[environmentName] |
| 17 | + if (environment) { |
| 18 | + environments.push(environment) |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + return environments |
| 23 | +} |
| 24 | + |
| 25 | +export async function runDevTools(builder: unknown) { |
| 26 | + const config = (builder as ViteBuilder).config |
| 27 | + for (const _environment of getDevToolsEnvironments(config)) { |
| 28 | + try { |
| 29 | + const { start } = await import('@vitejs/devtools/cli-commands') |
| 30 | + await start(config.devtools.config) |
| 31 | + } |
| 32 | + catch (error: any) { |
| 33 | + config.logger.error( |
| 34 | + `Failed to run Vite DevTools: ${error?.message || error?.stack || error}`, |
| 35 | + { error }, |
| 36 | + ) |
| 37 | + } |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +export function DevToolsIntegration(_options: DevToolsIntegrationOptions): Plugin { |
| 42 | + return { |
| 43 | + name: 'vite:devtools:integration', |
| 44 | + apply: 'build', |
| 45 | + configResolved: { |
| 46 | + order: 'post', |
| 47 | + handler(config) { |
| 48 | + // Enable `rolldownOptions.devtools` if the environment is selected, or for all environments by default. |
| 49 | + for (const environment of getDevToolsEnvironments(config)) { |
| 50 | + environment.build.rolldownOptions.devtools ??= {} |
| 51 | + } |
| 52 | + }, |
| 53 | + }, |
| 54 | + } |
| 55 | +} |
0 commit comments