|
| 1 | +import fs from 'fs'; |
| 2 | +import path from 'path'; |
| 3 | +import { optimizeDeps, ResolvedConfig } from 'vite'; |
| 4 | +import { ResolvedOptions } from './options'; |
| 5 | + |
| 6 | +// List of options that changes the prebundling result |
| 7 | +const PREBUNDLE_SENSITIVE_OPTIONS: (keyof ResolvedOptions)[] = [ |
| 8 | + 'compilerOptions', |
| 9 | + 'configFile', |
| 10 | + 'experimental', |
| 11 | + 'extensions', |
| 12 | + 'ignorePluginPreprocessors', |
| 13 | + 'preprocess' |
| 14 | +]; |
| 15 | + |
| 16 | +export async function handleOptimizeDeps(options: ResolvedOptions, viteConfig: ResolvedConfig) { |
| 17 | + if (!options.experimental.prebundleSvelteLibraries || !viteConfig.cacheDir) return; |
| 18 | + |
| 19 | + const viteMetadataPath = path.resolve(viteConfig.cacheDir, '_metadata.json'); |
| 20 | + |
| 21 | + if (!fs.existsSync(viteMetadataPath)) return; |
| 22 | + |
| 23 | + const svelteMetadataPath = path.resolve(viteConfig.cacheDir, '_svelte_metadata.json'); |
| 24 | + const currentSvelteMetadata = JSON.stringify(generateSvelteMetadata(options), (_, value) => { |
| 25 | + return typeof value === 'function' ? value.toString() : value; |
| 26 | + }); |
| 27 | + |
| 28 | + if (fs.existsSync(svelteMetadataPath)) { |
| 29 | + const existingSvelteMetadata = fs.readFileSync(svelteMetadataPath, 'utf8'); |
| 30 | + if (existingSvelteMetadata === currentSvelteMetadata) return; |
| 31 | + } |
| 32 | + |
| 33 | + await optimizeDeps(viteConfig, true); |
| 34 | + fs.writeFileSync(svelteMetadataPath, currentSvelteMetadata); |
| 35 | +} |
| 36 | + |
| 37 | +function generateSvelteMetadata(options: ResolvedOptions) { |
| 38 | + const metadata: Record<string, any> = {}; |
| 39 | + for (const key of PREBUNDLE_SENSITIVE_OPTIONS) { |
| 40 | + metadata[key] = options[key]; |
| 41 | + } |
| 42 | + return metadata; |
| 43 | +} |
0 commit comments