diff --git a/packages/create-vite/src/index.ts b/packages/create-vite/src/index.ts index 6090d1e37b1744..1a0a628d6e2956 100755 --- a/packages/create-vite/src/index.ts +++ b/packages/create-vite/src/index.ts @@ -289,9 +289,10 @@ const FRAMEWORKS: Framework[] = [ }, ] -const TEMPLATES = FRAMEWORKS.map( - (f) => (f.variants && f.variants.map((v) => v.name)) || [f.name], -).reduce((a, b) => a.concat(b), []) +const TEMPLATES = FRAMEWORKS.map((f) => f.variants.map((v) => v.name)).reduce( + (a, b) => a.concat(b), + [], +) const renameFiles: Record = { _gitignore: '.gitignore', @@ -394,8 +395,8 @@ async function init() { }), }, { - type: (framework: Framework) => - framework && framework.variants ? 'select' : null, + type: (framework: Framework | /* package name */ string) => + typeof framework === 'object' ? 'select' : null, name: 'variant', message: reset('Select a variant:'), choices: (framework: Framework) => diff --git a/packages/vite/src/client/overlay.ts b/packages/vite/src/client/overlay.ts index 63f570be488efb..5bef655c8f3a9a 100644 --- a/packages/vite/src/client/overlay.ts +++ b/packages/vite/src/client/overlay.ts @@ -264,23 +264,21 @@ export class ErrorOverlay extends HTMLElement { fileRE.lastIndex = 0 while ((match = fileRE.exec(text))) { const { 0: file, index } = match - if (index != null) { - const frag = text.slice(curIndex, index) - el.appendChild(document.createTextNode(frag)) - const link = document.createElement('a') - link.textContent = file - link.className = 'file-link' - link.onclick = () => { - fetch( - new URL( - `${base}__open-in-editor?file=${encodeURIComponent(file)}`, - import.meta.url, - ), - ) - } - el.appendChild(link) - curIndex += frag.length + file.length + const frag = text.slice(curIndex, index) + el.appendChild(document.createTextNode(frag)) + const link = document.createElement('a') + link.textContent = file + link.className = 'file-link' + link.onclick = () => { + fetch( + new URL( + `${base}__open-in-editor?file=${encodeURIComponent(file)}`, + import.meta.url, + ), + ) } + el.appendChild(link) + curIndex += frag.length + file.length } } } diff --git a/packages/vite/src/module-runner/hmrHandler.ts b/packages/vite/src/module-runner/hmrHandler.ts index 5844c0de844ef2..9615f4485eb57b 100644 --- a/packages/vite/src/module-runner/hmrHandler.ts +++ b/packages/vite/src/module-runner/hmrHandler.ts @@ -151,11 +151,11 @@ function getModulesEntrypoints( if (!module) { continue } - if (module.importers && !module.importers.size) { + if (!module.importers.size) { entrypoints.add(module.url) continue } - for (const importer of module.importers || []) { + for (const importer of module.importers) { getModulesEntrypoints(runner, [importer], visited, entrypoints) } } @@ -167,7 +167,7 @@ function findAllEntrypoints( entrypoints = new Set(), ): Set { for (const mod of runner.evaluatedModules.idToModuleMap.values()) { - if (mod.importers && !mod.importers.size) { + if (!mod.importers.size) { entrypoints.add(mod.url) } } diff --git a/packages/vite/src/module-runner/sourcemap/interceptor.ts b/packages/vite/src/module-runner/sourcemap/interceptor.ts index eb4f41f83e68a2..c25837e08ad3a8 100644 --- a/packages/vite/src/module-runner/sourcemap/interceptor.ts +++ b/packages/vite/src/module-runner/sourcemap/interceptor.ts @@ -210,7 +210,7 @@ function mapSourcePosition(position: OriginalMapping) { } // Resolve the source URL relative to the URL of the source map - if (sourceMap && sourceMap.map && sourceMap.url) { + if (sourceMap.map && sourceMap.url) { const originalPosition = getOriginalPosition(sourceMap.map, position) // Only return the original position if a matching line was found. If no diff --git a/packages/vite/src/node/build.ts b/packages/vite/src/node/build.ts index 8dd3df266c58f3..cb654dd2d35719 100644 --- a/packages/vite/src/node/build.ts +++ b/packages/vite/src/node/build.ts @@ -391,7 +391,7 @@ export function resolveBuildEnvironmentOptions( logger: Logger, consumer: 'client' | 'server' | undefined, ): ResolvedBuildEnvironmentOptions { - const deprecatedPolyfillModulePreload = raw?.polyfillModulePreload + const deprecatedPolyfillModulePreload = raw.polyfillModulePreload const { polyfillModulePreload, ...rest } = raw raw = rest if (deprecatedPolyfillModulePreload !== undefined) { @@ -543,7 +543,7 @@ async function buildEnvironment( const resolve = (p: string) => path.resolve(root, p) const input = libOptions - ? options.rollupOptions?.input || + ? options.rollupOptions.input || (typeof libOptions.entry === 'string' ? resolve(libOptions.entry) : Array.isArray(libOptions.entry) @@ -556,7 +556,7 @@ async function buildEnvironment( )) : typeof options.ssr === 'string' ? resolve(options.ssr) - : options.rollupOptions?.input || resolve('index.html') + : options.rollupOptions.input || resolve('index.html') if (ssr && typeof input === 'string' && input.endsWith('.html')) { throw new Error( @@ -596,7 +596,7 @@ async function buildEnvironment( output: options.rollupOptions.output, input, plugins, - external: options.rollupOptions?.external, + external: options.rollupOptions.external, onwarn(warning, warn) { onRollupWarning(warning, warn, environment) }, @@ -743,7 +743,7 @@ async function buildEnvironment( // resolve lib mode outputs const outputs = resolveBuildOutputs( - options.rollupOptions?.output, + options.rollupOptions.output, libOptions, logger, ) @@ -760,7 +760,7 @@ async function buildEnvironment( const resolvedOutDirs = getResolvedOutDirs( root, options.outDir, - options.rollupOptions?.output, + options.rollupOptions.output, ) const emptyOutDir = resolveEmptyOutDir( options.emptyOutDir, @@ -1058,7 +1058,7 @@ export function onRollupWarning( } clearLine() - const userOnWarn = environment.config.build.rollupOptions?.onwarn + const userOnWarn = environment.config.build.rollupOptions.onwarn if (userOnWarn) { userOnWarn(warning, viteWarn) } else { @@ -1441,7 +1441,7 @@ export class BuildEnvironment extends BaseEnvironment { if (setup?.options) { options = mergeConfig( options, - setup?.options, + setup.options, ) as ResolvedEnvironmentOptions } super(name, config, options) diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index 783f441fb7ea9f..d396990ba75425 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -25,6 +25,7 @@ import { FS_PREFIX, } from './constants' import type { + FalsyPlugin, HookHandler, Plugin, PluginOption, @@ -1002,7 +1003,7 @@ export async function resolveConfig( mode = inlineConfig.mode || config.mode || mode configEnv.mode = mode - const filterPlugin = (p: Plugin) => { + const filterPlugin = (p: Plugin | FalsyPlugin): p is Plugin => { if (!p) { return false } else if (!p.apply) { @@ -1015,9 +1016,9 @@ export async function resolveConfig( } // resolve plugins - const rawPlugins = ( - (await asyncFlatten(config.plugins || [])) as Plugin[] - ).filter(filterPlugin) + const rawPlugins = (await asyncFlatten(config.plugins || [])).filter( + filterPlugin, + ) const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawPlugins) @@ -1068,12 +1069,12 @@ export async function resolveConfig( // Backward compatibility: server.warmup.clientFiles/ssrFiles -> environment.dev.warmup const warmupOptions = config.server?.warmup if (warmupOptions?.clientFiles) { - configEnvironmentsClient.dev.warmup = warmupOptions?.clientFiles + configEnvironmentsClient.dev.warmup = warmupOptions.clientFiles } if (warmupOptions?.ssrFiles) { configEnvironmentsSsr ??= {} configEnvironmentsSsr.dev ??= {} - configEnvironmentsSsr.dev.warmup = warmupOptions?.ssrFiles + configEnvironmentsSsr.dev.warmup = warmupOptions.ssrFiles } // Backward compatibility: merge ssr into environments.ssr.config as defaults @@ -1102,11 +1103,7 @@ export async function resolveConfig( } // The client and ssr environment configs can't be removed by the user in the config hook - if ( - !config.environments || - !config.environments.client || - (!config.environments.ssr && !isBuild) - ) { + if (!config.environments.client || (!config.environments.ssr && !isBuild)) { throw new Error( 'Required environments configuration were stripped out in the config hook', ) @@ -1244,7 +1241,7 @@ export async function resolveConfig( ? !isBuild || config.build?.ssr ? '/' : './' - : (resolveBaseUrl(config.base, isBuild, logger) ?? configDefaults.base) + : resolveBaseUrl(config.base, isBuild, logger) // resolve cache directory const pkgDir = findNearestPackageData(resolvedRoot, packageCache)?.dir @@ -1301,7 +1298,7 @@ export async function resolveConfig( // And Plugins may also have cached that could be corrupted by being used in these extra rollup calls. // So we need to separate the worker plugin from the plugin that vite needs to run. const rawWorkerUserPlugins = ( - (await asyncFlatten(createUserWorkerPlugins?.() || [])) as Plugin[] + await asyncFlatten(createUserWorkerPlugins?.() || []) ).filter(filterPlugin) // resolve worker @@ -1577,7 +1574,7 @@ assetFileNames isn't equal for every build.rollupOptions.output. A single patter * electron or expects to deploy */ export function resolveBaseUrl( - base: UserConfig['base'] = '/', + base: UserConfig['base'] = configDefaults.base, isBuild: boolean, logger: Logger, ): string { @@ -1846,7 +1843,7 @@ async function bundleConfigFile( const { text } = result.outputFiles[0] return { code: text, - dependencies: result.metafile ? Object.keys(result.metafile.inputs) : [], + dependencies: Object.keys(result.metafile.inputs), } } @@ -1934,11 +1931,9 @@ async function runConfigHook( for (const p of getSortedPluginsByHook('config', plugins)) { const hook = p.config const handler = getHookHandler(hook) - if (handler) { - const res = await handler(conf, configEnv) - if (res && res !== conf) { - conf = mergeConfig(conf, res) - } + const res = await handler(conf, configEnv) + if (res && res !== conf) { + conf = mergeConfig(conf, res) } } @@ -1955,15 +1950,13 @@ async function runConfigEnvironmentHook( for (const p of getSortedPluginsByHook('configEnvironment', plugins)) { const hook = p.configEnvironment const handler = getHookHandler(hook) - if (handler) { - for (const name of environmentNames) { - const res = await handler(name, environments[name], { - ...configEnv, - isSsrTargetWebworker: isSsrTargetWebworkerSet && name === 'ssr', - }) - if (res) { - environments[name] = mergeConfig(environments[name], res) - } + for (const name of environmentNames) { + const res = await handler(name, environments[name], { + ...configEnv, + isSsrTargetWebworker: isSsrTargetWebworkerSet && name === 'ssr', + }) + if (res) { + environments[name] = mergeConfig(environments[name], res) } } } @@ -1977,7 +1970,7 @@ function optimizeDepsDisabledBackwardCompatibility( const optimizeDepsDisabled = optimizeDeps.disabled if (optimizeDepsDisabled !== undefined) { if (optimizeDepsDisabled === true || optimizeDepsDisabled === 'dev') { - const commonjsOptionsInclude = resolved.build?.commonjsOptions?.include + const commonjsOptionsInclude = resolved.build.commonjsOptions.include const commonjsPluginDisabled = Array.isArray(commonjsOptionsInclude) && commonjsOptionsInclude.length === 0 diff --git a/packages/vite/src/node/external.ts b/packages/vite/src/node/external.ts index 58d30cfc096371..7b95d6aa92b959 100644 --- a/packages/vite/src/node/external.ts +++ b/packages/vite/src/node/external.ts @@ -61,7 +61,7 @@ export function createIsConfiguredAsExternal( !(Array.isArray(noExternal) && noExternal.length === 0) && createFilter(undefined, noExternal, { resolve: false }) - const targetConditions = resolve.externalConditions || [] + const targetConditions = resolve.externalConditions const resolveOptions: InternalResolveOptions = { ...resolve, diff --git a/packages/vite/src/node/optimizer/esbuildDepPlugin.ts b/packages/vite/src/node/optimizer/esbuildDepPlugin.ts index 7afbb7fbdea82f..1bdb2d2125d539 100644 --- a/packages/vite/src/node/optimizer/esbuildDepPlugin.ts +++ b/packages/vite/src/node/optimizer/esbuildDepPlugin.ts @@ -57,7 +57,7 @@ export function esbuildDepPlugin( // remove optimizable extensions from `externalTypes` list const allExternalTypes = extensions - ? externalTypes.filter((type) => !extensions?.includes('.' + type)) + ? externalTypes.filter((type) => !extensions.includes('.' + type)) : externalTypes // use separate package cache for optimizer as it caches paths around node_modules diff --git a/packages/vite/src/node/optimizer/index.ts b/packages/vite/src/node/optimizer/index.ts index f52bd879149a8f..36503d4ee37f5e 100644 --- a/packages/vite/src/node/optimizer/index.ts +++ b/packages/vite/src/node/optimizer/index.ts @@ -343,7 +343,7 @@ let firstLoadCachedDepOptimizationMetadata = true */ export async function loadCachedDepOptimizationMetadata( environment: Environment, - force = environment.config.optimizeDeps?.force ?? false, + force = environment.config.optimizeDeps.force ?? false, asCommand = false, ): Promise { const log = asCommand ? environment.logger.info : debug @@ -751,7 +751,7 @@ async function prepareEsbuildOptimizerRun( const { optimizeDeps } = environment.config const { plugins: pluginsFromConfig = [], ...esbuildOptions } = - optimizeDeps?.esbuildOptions ?? {} + optimizeDeps.esbuildOptions ?? {} await Promise.all( Object.keys(depsInfo).map(async (id) => { @@ -790,7 +790,7 @@ async function prepareEsbuildOptimizerRun( ? 'browser' : 'node') - const external = [...(optimizeDeps?.exclude ?? [])] + const external = [...(optimizeDeps.exclude ?? [])] const plugins = [...pluginsFromConfig] if (external.length) { @@ -837,7 +837,7 @@ export async function addManuallyIncludedOptimizeDeps( ): Promise { const { logger } = environment const { optimizeDeps } = environment.config - const optimizeDepsInclude = optimizeDeps?.include ?? [] + const optimizeDepsInclude = optimizeDeps.include ?? [] if (optimizeDepsInclude.length) { const unableToOptimize = (id: string, msg: string) => { if (optimizeDepsInclude.includes(id)) { @@ -1083,7 +1083,7 @@ export async function extractExportsData( const { optimizeDeps } = environment.config - const esbuildOptions = optimizeDeps?.esbuildOptions ?? {} + const esbuildOptions = optimizeDeps.esbuildOptions ?? {} if (optimizeDeps.extensions?.some((ext) => filePath.endsWith(ext))) { // For custom supported extensions, build the entry file to transform it into JS, // and then parse with es-module-lexer. Note that the `bundle` option is not `true`, @@ -1138,7 +1138,7 @@ function needsInterop( exportsData: ExportsData, output?: { exports: string[] }, ): boolean { - if (environment.config.optimizeDeps?.needsInterop?.includes(id)) { + if (environment.config.optimizeDeps.needsInterop?.includes(id)) { return true } const { hasModuleSyntax, exports } = exportsData @@ -1154,9 +1154,8 @@ function needsInterop( const generatedExports: string[] = output.exports if ( - !generatedExports || - (isSingleDefaultExport(generatedExports) && - !isSingleDefaultExport(exports)) + isSingleDefaultExport(generatedExports) && + !isSingleDefaultExport(exports) ) { return true } @@ -1217,15 +1216,15 @@ function getConfigHash(environment: Environment): string { assetsInclude: config.assetsInclude, plugins: config.plugins.map((p) => p.name), optimizeDeps: { - include: optimizeDeps?.include + include: optimizeDeps.include ? unique(optimizeDeps.include).sort() : undefined, - exclude: optimizeDeps?.exclude + exclude: optimizeDeps.exclude ? unique(optimizeDeps.exclude).sort() : undefined, esbuildOptions: { - ...optimizeDeps?.esbuildOptions, - plugins: optimizeDeps?.esbuildOptions?.plugins?.map((p) => p.name), + ...optimizeDeps.esbuildOptions, + plugins: optimizeDeps.esbuildOptions?.plugins?.map((p) => p.name), }, }, }, @@ -1392,6 +1391,6 @@ const safeRename = promisify(function gracefulRename( if (backoff < 100) backoff += 10 return } - if (cb) cb(er) + cb(er) }) }) diff --git a/packages/vite/src/node/optimizer/scan.ts b/packages/vite/src/node/optimizer/scan.ts index 10bb9960cb759e..5c7562c5ba8f12 100644 --- a/packages/vite/src/node/optimizer/scan.ts +++ b/packages/vite/src/node/optimizer/scan.ts @@ -183,7 +183,7 @@ export function scanImports(environment: ScanEnvironment): { }) }) } - if (!context || scanContext?.cancelled) { + if (!context || scanContext.cancelled) { disposeContext() return { deps: {}, missing: {} } } @@ -248,7 +248,7 @@ async function computeEntries(environment: ScanEnvironment) { let entries: string[] = [] const explicitEntryPatterns = environment.config.optimizeDeps.entries - const buildInput = environment.config.build.rollupOptions?.input + const buildInput = environment.config.build.rollupOptions.input if (explicitEntryPatterns) { entries = await globEntries(explicitEntryPatterns, environment) @@ -295,9 +295,9 @@ async function prepareEsbuildScanner( entries: string[], deps: Record, missing: Record, - scanContext?: { cancelled: boolean }, + scanContext: { cancelled: boolean }, ): Promise { - if (scanContext?.cancelled) return + if (scanContext.cancelled) return const plugin = esbuildScanPlugin(environment, deps, missing, entries) diff --git a/packages/vite/src/node/plugin.ts b/packages/vite/src/node/plugin.ts index 1f76300037a2f9..033b907d98706b 100644 --- a/packages/vite/src/node/plugin.ts +++ b/packages/vite/src/node/plugin.ts @@ -331,7 +331,7 @@ export type PluginWithRequiredHook = Plugin & { type Thenable = T | Promise -type FalsyPlugin = false | null | undefined +export type FalsyPlugin = false | null | undefined export type PluginOption = Thenable diff --git a/packages/vite/src/node/plugins/asset.ts b/packages/vite/src/node/plugins/asset.ts index d6f84ebc42966a..b9447d9cf17f68 100644 --- a/packages/vite/src/node/plugins/asset.ts +++ b/packages/vite/src/node/plugins/asset.ts @@ -305,7 +305,7 @@ export async function fileToDevUrl( if (skipBase) { return rtn } - const base = joinUrlSegments(config.server?.origin ?? '', config.decodedBase) + const base = joinUrlSegments(config.server.origin ?? '', config.decodedBase) return joinUrlSegments(base, removeLeadingSlash(rtn)) } diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 5ae6a93b7ad462..04c0f87982fa2e 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -306,7 +306,7 @@ export function cssPlugin(config: ResolvedConfig): Plugin { let preprocessorWorkerController: PreprocessorWorkerController | undefined // warm up cache for resolved postcss config - if (config.css?.transformer !== 'lightningcss') { + if (config.css.transformer !== 'lightningcss') { resolvePostcssConfig(config).catch(() => { /* will be handled later */ }) @@ -550,7 +550,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { if (config.command === 'serve') { const getContentWithSourcemap = async (content: string) => { - if (config.css?.devSourcemap) { + if (config.css.devSourcemap) { const sourcemap = this.getCombinedSourcemap() if (sourcemap.mappings) { await injectSourcesContent(sourcemap, cleanUrl(id), config.logger) @@ -911,7 +911,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { // will be populated in order they are used by entry points const dynamicImports = new Set() - function collect(chunk: OutputChunk | OutputAsset) { + function collect(chunk: OutputChunk | OutputAsset | undefined) { if (!chunk || chunk.type !== 'chunk' || collected.has(chunk)) return collected.add(chunk) @@ -1197,7 +1197,7 @@ async function compileCSSPreprocessors( workerController: PreprocessorWorkerController, ): Promise<{ code: string; map?: ExistingRawSourceMap; deps?: Set }> { const { config } = environment - const { preprocessorOptions, devSourcemap } = config.css ?? {} + const { preprocessorOptions, devSourcemap } = config.css const atImportResolvers = getAtImportResolvers( environment.getTopLevelConfig(), ) @@ -1222,7 +1222,7 @@ async function compileCSSPreprocessors( } let deps: Set | undefined - if (preprocessResult.deps) { + if (preprocessResult.deps.length > 0) { const normalizedFilename = normalizePath(opts.filename) // sometimes sass registers the file itself as a dep deps = new Set( @@ -1270,11 +1270,11 @@ async function compileCSS( deps?: Set }> { const { config } = environment - if (config.css?.transformer === 'lightningcss') { + if (config.css.transformer === 'lightningcss') { return compileLightningCSS(id, code, environment, urlReplacer) } - const { modules: modulesOptions, devSourcemap } = config.css || {} + const { modules: modulesOptions, devSourcemap } = config.css const isModule = modulesOptions !== false && cssModuleRE.test(id) // although at serve time it can work without processing, we do need to // crawl them in order to register watch dependencies. @@ -1318,10 +1318,8 @@ async function compileCSS( const atImportResolvers = getAtImportResolvers( environment.getTopLevelConfig(), ) - const postcssOptions = (postcssConfig && postcssConfig.options) || {} - - const postcssPlugins = - postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : [] + const postcssOptions = postcssConfig?.options ?? {} + const postcssPlugins = postcssConfig?.plugins.slice() ?? [] if (needInlineImport) { postcssPlugins.unshift( @@ -1677,7 +1675,7 @@ async function resolvePostcssConfig( } // inline postcss config via vite config - const inlineOptions = config.css?.postcss + const inlineOptions = config.css.postcss if (isObject(inlineOptions)) { const options = { ...inlineOptions } @@ -1918,7 +1916,7 @@ async function minifyCSS( if (config.build.cssMinify === 'lightningcss') { const { code, warnings } = (await importLightningCSS()).transform({ - ...config.css?.lightningcss, + ...config.css.lightningcss, targets: convertTargets(config.build.cssTarget), cssModules: undefined, // TODO: Pass actual filename here, which can also be passed to esbuild's @@ -2164,7 +2162,7 @@ function cleanScssBugUrl(url: string) { // check bug via `window` and `location` global typeof window !== 'undefined' && typeof location !== 'undefined' && - typeof location?.href === 'string' + typeof location.href === 'string' ) { const prefix = location.href.replace(/\/$/, '') return url.replace(prefix, '') @@ -2254,7 +2252,7 @@ const makeScssWorker = ( done, ) => { internalImporter(url, importer, options.filename).then((data) => - done?.(data), + done(data), ) } const importer = [_internalImporter] @@ -2726,13 +2724,10 @@ const makeLessWorker = ( '@', resolvers.less, ) - if (result) { - return { - resolved, - contents: 'contents' in result ? result.contents : undefined, - } + return { + resolved, + contents: 'contents' in result ? result.contents : undefined, } - return result } const worker = new WorkerWithFallback( @@ -2886,7 +2881,8 @@ const lessProcessor = ( return { code: '', error: normalizedError, deps: [] } } - const map: ExistingRawSourceMap = result.map && JSON.parse(result.map) + const map: ExistingRawSourceMap | undefined = + result.map && JSON.parse(result.map) if (map) { delete map.sourcesContent } @@ -3148,14 +3144,14 @@ async function compileLightningCSS( ? (await importLightningCSS()).transformStyleAttribute({ filename, code: Buffer.from(src), - targets: config.css?.lightningcss?.targets, + targets: config.css.lightningcss?.targets, minify: config.isProduction && !!config.build.cssMinify, analyzeDependencies: true, }) : await ( await importLightningCSS() ).bundleAsync({ - ...config.css?.lightningcss, + ...config.css.lightningcss, filename, resolver: { read(filePath) { @@ -3192,10 +3188,10 @@ async function compileLightningCSS( sourceMap: config.command === 'build' ? !!config.build.sourcemap - : config.css?.devSourcemap, + : config.css.devSourcemap, analyzeDependencies: true, cssModules: cssModuleRE.test(id) - ? (config.css?.lightningcss?.cssModules ?? true) + ? (config.css.lightningcss?.cssModules ?? true) : undefined, }) } catch (e) { diff --git a/packages/vite/src/node/plugins/esbuild.ts b/packages/vite/src/node/plugins/esbuild.ts index 6d3ffc86f33b06..54e0f5df4963a5 100644 --- a/packages/vite/src/node/plugins/esbuild.ts +++ b/packages/vite/src/node/plugins/esbuild.ts @@ -265,7 +265,7 @@ export function esbuildPlugin(config: ResolvedConfig): Plugin { }, } - let server: ViteDevServer + let server: ViteDevServer | undefined return { name: 'vite:esbuild', diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index 25a23e98c7a7d0..2e9b16668f36d6 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -419,9 +419,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { // for each encountered asset url, rewrite original html so that it // references the post-build location, ignoring empty attributes and // attributes that directly reference named output. - const namedOutput = Object.keys( - config?.build?.rollupOptions?.input || {}, - ) + const namedOutput = Object.keys(config.build.rollupOptions.input || {}) const processAssetUrl = async (url: string, shouldInline?: boolean) => { if ( url !== '' && // Empty attribute diff --git a/packages/vite/src/node/plugins/importAnalysis.ts b/packages/vite/src/node/plugins/importAnalysis.ts index f13d920fb83647..a5e960c8e3bb68 100644 --- a/packages/vite/src/node/plugins/importAnalysis.ts +++ b/packages/vite/src/node/plugins/importAnalysis.ts @@ -175,9 +175,6 @@ function extractImportedBindings( specifier: match.groups!.specifier, } const parsed = parseStaticImport(staticImport) - if (!parsed) { - return - } if (parsed.namespacedImport) { bindings.add('*') } @@ -223,7 +220,7 @@ function extractImportedBindings( export function importAnalysisPlugin(config: ResolvedConfig): Plugin { const { root, base } = config const clientPublicPath = path.posix.join(base, CLIENT_PUBLIC_PATH) - const enablePartialAccept = config.experimental?.hmrPartialAccept + const enablePartialAccept = config.experimental.hmrPartialAccept const matchAlias = getAliasPatternMatcher(config.resolve.alias) let _env: string | undefined @@ -354,6 +351,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin { throw e }) + // NOTE: resolved.meta is undefined in dev if (!resolved || resolved.meta?.['vite:alias']?.noResolved) { // in ssr, we should let node handle the missing modules if (ssr) { diff --git a/packages/vite/src/node/plugins/importAnalysisBuild.ts b/packages/vite/src/node/plugins/importAnalysisBuild.ts index d883e0c4cd222e..98e4fcd32d3e21 100644 --- a/packages/vite/src/node/plugins/importAnalysisBuild.ts +++ b/packages/vite/src/node/plugins/importAnalysisBuild.ts @@ -705,7 +705,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin { '', ) chunk.code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}` - } else if (buildSourcemap) { + } else { const mapAsset = bundle[chunk.fileName + '.map'] if (mapAsset && mapAsset.type === 'asset') { mapAsset.source = map.toString() diff --git a/packages/vite/src/node/plugins/json.ts b/packages/vite/src/node/plugins/json.ts index d531ee80efac7f..33c1c0d27aeaac 100644 --- a/packages/vite/src/node/plugins/json.ts +++ b/packages/vite/src/node/plugins/json.ts @@ -76,9 +76,9 @@ export function jsonPlugin( if ( options.stringify === true || - // use 10kB as a threshold + // use 10kB as a threshold for 'auto' // https://v8.dev/blog/cost-of-javascript-2019#:~:text=A%20good%20rule%20of%20thumb%20is%20to%20apply%20this%20technique%20for%20objects%20of%2010%20kB%20or%20larger - (options.stringify === 'auto' && json.length > 10 * 1000) + json.length > 10 * 1000 ) { // during build, parse then double-stringify to remove all // unnecessary whitespaces to reduce bundle size. diff --git a/packages/vite/src/node/plugins/manifest.ts b/packages/vite/src/node/plugins/manifest.ts index 0263902d4c2836..c46ac8a61ce2f3 100644 --- a/packages/vite/src/node/plugins/manifest.ts +++ b/packages/vite/src/node/plugins/manifest.ts @@ -175,7 +175,7 @@ export function manifestPlugin(): Plugin { } state.outputCount++ - const output = buildOptions.rollupOptions?.output + const output = buildOptions.rollupOptions.output const outputLength = Array.isArray(output) ? output.length : 1 if (state.outputCount >= outputLength) { this.emitFile({ diff --git a/packages/vite/src/node/plugins/preAlias.ts b/packages/vite/src/node/plugins/preAlias.ts index 7422544bb98d79..b75f59542902d2 100644 --- a/packages/vite/src/node/plugins/preAlias.ts +++ b/packages/vite/src/node/plugins/preAlias.ts @@ -34,7 +34,7 @@ export function preAliasPlugin(config: ResolvedConfig): Plugin { importer && depsOptimizer && bareImportRE.test(id) && - !options?.scan && + !options.scan && id !== '@vite/client' && id !== '@vite/env' ) { @@ -120,9 +120,6 @@ function matches(pattern: string | RegExp, importee: string) { function getAliasPatterns( entries: (AliasOptions | undefined) & Alias[], ): (string | RegExp)[] { - if (!entries) { - return [] - } if (Array.isArray(entries)) { return entries.map((entry) => entry.find) } diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index f75798b84abe8e..2306a2600a1c50 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -223,7 +223,7 @@ export function resolvePlugin( // this is passed by @rollup/plugin-commonjs const isRequire: boolean = - resolveOpts?.custom?.['node-resolve']?.isRequire ?? false + resolveOpts.custom?.['node-resolve']?.isRequire ?? false const currentEnvironmentOptions = this.environment.config @@ -231,7 +231,7 @@ export function resolvePlugin( isRequire, ...currentEnvironmentOptions.resolve, ...resolveOptions, // plugin options + resolve options overrides - scan: resolveOpts?.scan ?? resolveOptions.scan, + scan: resolveOpts.scan ?? resolveOptions.scan, } const resolvedImports = resolveSubpathImports(id, importer, options) @@ -250,7 +250,7 @@ export function resolvePlugin( ) { options.isFromTsImporter = true } else { - const moduleLang = this.getModuleInfo(importer)?.meta?.vite?.lang + const moduleLang = this.getModuleInfo(importer)?.meta.vite?.lang options.isFromTsImporter = moduleLang && isTsRequest(`.${moduleLang}`) } } @@ -707,7 +707,7 @@ export function tryNodeResolve( const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(id) let basedir: string - if (dedupe?.includes(pkgId)) { + if (dedupe.includes(pkgId)) { basedir = root } else if ( importer && @@ -725,7 +725,7 @@ export function tryNodeResolve( // check if it's a self reference dep. const selfPackageData = findNearestPackageData(basedir, packageCache) selfPkg = - selfPackageData?.data.exports && selfPackageData?.data.name === pkgId + selfPackageData?.data.exports && selfPackageData.data.name === pkgId ? selfPackageData : null } @@ -778,7 +778,7 @@ export function tryNodeResolve( let resolvedId = id if ( deepMatch && - !pkg?.data.exports && + !pkg.data.exports && path.extname(id) !== path.extname(resolved.id) ) { // id date-fns/locale diff --git a/packages/vite/src/node/plugins/splitVendorChunk.ts b/packages/vite/src/node/plugins/splitVendorChunk.ts index 39a50a02dbf28f..ce2a5eed98754c 100644 --- a/packages/vite/src/node/plugins/splitVendorChunk.ts +++ b/packages/vite/src/node/plugins/splitVendorChunk.ts @@ -102,7 +102,7 @@ export function splitVendorChunkPlugin(): Plugin { const cache = new SplitVendorChunkCache() caches.push(cache) const build = config.build ?? {} - const format = output?.format + const format = output.format if (!build.ssr && !build.lib && format !== 'umd' && format !== 'iife') { return splitVendorChunk({ cache }) } @@ -110,7 +110,7 @@ export function splitVendorChunkPlugin(): Plugin { return { name: 'vite:split-vendor-chunk', config(config) { - let outputs = config?.build?.rollupOptions?.output + let outputs = config.build?.rollupOptions?.output if (outputs) { outputs = arraify(outputs) for (const output of outputs) { diff --git a/packages/vite/src/node/preview.ts b/packages/vite/src/node/preview.ts index a50cc2a6609a03..2031538cc5c356 100644 --- a/packages/vite/src/node/preview.ts +++ b/packages/vite/src/node/preview.ts @@ -119,8 +119,7 @@ export async function preview( true, ) - const clientOutDir = - config.environments.client.build.outDir ?? config.build.outDir + const clientOutDir = config.environments.client.build.outDir const distDir = path.resolve(config.root, clientOutDir) if ( !fs.existsSync(distDir) && @@ -140,7 +139,7 @@ export async function preview( const httpServer = await resolveHttpServer( config.preview, app, - await resolveHttpsConfig(config.preview?.https), + await resolveHttpsConfig(config.preview.https), ) setClientErrorHandler(httpServer, config.logger) @@ -261,7 +260,7 @@ export async function preview( ) if (options.open) { - const url = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0] + const url = server.resolvedUrls.local[0] ?? server.resolvedUrls.network[0] if (url) { const path = typeof options.open === 'string' ? new URL(options.open, url).href : url diff --git a/packages/vite/src/node/server/environment.ts b/packages/vite/src/node/server/environment.ts index 6b126122ee65dc..8268419e1f4a8f 100644 --- a/packages/vite/src/node/server/environment.ts +++ b/packages/vite/src/node/server/environment.ts @@ -234,12 +234,12 @@ export class DevEnvironment extends BaseEnvironment { async close(): Promise { this._closing = true - this._crawlEndFinder?.cancel() + this._crawlEndFinder.cancel() await Promise.allSettled([ this.pluginContainer.close(), this.depsOptimizer?.close(), // WebSocketServer is independent of HotChannel and should not be closed on environment close - isWebSocketServer in this.hot ? Promise.resolve() : this.hot.close?.(), + isWebSocketServer in this.hot ? Promise.resolve() : this.hot.close(), (async () => { while (this._pendingRequests.size > 0) { await Promise.allSettled( diff --git a/packages/vite/src/node/server/hmr.ts b/packages/vite/src/node/server/hmr.ts index fa15d0895803bf..6b6b334202c579 100644 --- a/packages/vite/src/node/server/hmr.ts +++ b/packages/vite/src/node/server/hmr.ts @@ -364,7 +364,7 @@ export function getSortedPluginsByHotUpdateHook( const sortedHotUpdatePluginsCache = new WeakMap() function getSortedHotUpdatePlugins(environment: Environment): Plugin[] { - let sortedPlugins = sortedHotUpdatePluginsCache.get(environment) as Plugin[] + let sortedPlugins = sortedHotUpdatePluginsCache.get(environment) if (!sortedPlugins) { sortedPlugins = getSortedPluginsByHotUpdateHook(environment.plugins) sortedHotUpdatePluginsCache.set(environment, sortedPlugins) @@ -989,7 +989,7 @@ export function lexAcceptedHmrDeps( // in both case this indicates a self-accepting module return true // done } - } else if (state === LexerState.inArray) { + } else { if (char === `]`) { return false // done } else if (char === ',') { @@ -1174,9 +1174,7 @@ export function createDeprecatedHotBroadcaster( return broadcaster }, close() { - return Promise.all( - broadcaster.channels.map((channel) => channel.close?.()), - ) + return Promise.all(broadcaster.channels.map((channel) => channel.close())) }, } return broadcaster diff --git a/packages/vite/src/node/server/index.ts b/packages/vite/src/node/server/index.ts index 13912a3f13f26f..5828a90be3043d 100644 --- a/packages/vite/src/node/server/index.ts +++ b/packages/vite/src/node/server/index.ts @@ -443,7 +443,7 @@ export async function _createServer( const resolvedOutDirs = getResolvedOutDirs( config.root, config.build.outDir, - config.build.rollupOptions?.output, + config.build.rollupOptions.output, ) const emptyOutDir = resolveEmptyOutDir( config.build.emptyOutDir, @@ -551,8 +551,7 @@ export async function _createServer( return ssrTransform(code, inMap, url, originalCode, { json: { stringify: - config.json?.stringify === true && - config.json.namedExports !== true, + config.json.stringify === true && config.json.namedExports !== true, }, }) }, diff --git a/packages/vite/src/node/server/middlewares/indexHtml.ts b/packages/vite/src/node/server/middlewares/indexHtml.ts index ae432900d46756..228dce2ae7befa 100644 --- a/packages/vite/src/node/server/middlewares/indexHtml.ts +++ b/packages/vite/src/node/server/middlewares/indexHtml.ts @@ -375,19 +375,13 @@ const devHtmlHook: IndexHtmlTransformHook = async ( environment: server!.environments.client, }) let content = '' - if (result) { - if (result.map && 'version' in result.map) { - if (result.map.mappings) { - await injectSourcesContent( - result.map, - proxyModulePath, - config.logger, - ) - } - content = getCodeWithSourcemap('css', result.code, result.map) - } else { - content = result.code + if (result.map && 'version' in result.map) { + if (result.map.mappings) { + await injectSourcesContent(result.map, proxyModulePath, config.logger) } + content = getCodeWithSourcemap('css', result.code, result.map) + } else { + content = result.code } s.overwrite(start, end, content) }), diff --git a/packages/vite/src/node/server/middlewares/transform.ts b/packages/vite/src/node/server/middlewares/transform.ts index abd790b1ac4d3f..22f06cfbacfc5e 100644 --- a/packages/vite/src/node/server/middlewares/transform.ts +++ b/packages/vite/src/node/server/middlewares/transform.ts @@ -60,7 +60,7 @@ export function cachedTransformMiddleware( const moduleByEtag = environment.moduleGraph.getModuleByEtag(ifNoneMatch) if ( moduleByEtag?.transformResult?.etag === ifNoneMatch && - moduleByEtag?.url === req.url + moduleByEtag.url === req.url ) { // For CSS requests, if the same CSS file is imported in a module, // the browser sends the request for the direct CSS request with the etag diff --git a/packages/vite/src/node/server/mixedModuleGraph.ts b/packages/vite/src/node/server/mixedModuleGraph.ts index 28fad52e5de670..51fdc3ad1d3809 100644 --- a/packages/vite/src/node/server/mixedModuleGraph.ts +++ b/packages/vite/src/node/server/mixedModuleGraph.ts @@ -659,7 +659,7 @@ function createBackwardCompatibleFileToModulesMap( } } if (!found) { - modules?.add(ssrModule) + modules.add(ssrModule) } } } diff --git a/packages/vite/src/node/server/pluginContainer.ts b/packages/vite/src/node/server/pluginContainer.ts index 06389988114daa..c570c020a7bdfc 100644 --- a/packages/vite/src/node/server/pluginContainer.ts +++ b/packages/vite/src/node/server/pluginContainer.ts @@ -288,10 +288,9 @@ class EnvironmentPluginContainer { const parallelPromises: Promise[] = [] for (const plugin of this.getSortedPlugins(hookName)) { // Don't throw here if closed, so buildEnd and closeBundle hooks can finish running - const hook = plugin[hookName] - if (!hook) continue if (condition && !condition(plugin)) continue + const hook = plugin[hookName] const handler: Function = getHookHandler(hook) if ((hook as { sequential?: boolean }).sequential) { await Promise.all(parallelPromises) @@ -360,7 +359,6 @@ class EnvironmentPluginContainer { for (const plugin of this.getSortedPlugins('resolveId')) { if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError() - if (!plugin.resolveId) continue if (skip?.has(plugin)) continue ctx._plugin = plugin @@ -423,7 +421,6 @@ class EnvironmentPluginContainer { for (const plugin of this.getSortedPlugins('load')) { if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError() - if (!plugin.load) continue ctx._plugin = plugin const handler = getHookHandler(plugin.load) const result = await this.handleHookPromise( @@ -458,7 +455,6 @@ class EnvironmentPluginContainer { for (const plugin of this.getSortedPlugins('transform')) { if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError() - if (!plugin.transform) continue ctx._updateActiveInfo(plugin, id, code) const start = debugPluginTransform ? performance.now() : 0 @@ -564,7 +560,7 @@ class PluginContext implements Omit { }, ) { let skip: Set | undefined - if (options?.skipSelf !== false && this._plugin) { + if (options?.skipSelf !== false) { skip = new Set(this._resolveSkips) skip.add(this._plugin) } @@ -688,7 +684,7 @@ class PluginContext implements Omit { if (err.pluginCode) { return err // The plugin likely called `this.error` } - if (this._plugin) err.plugin = this._plugin.name + err.plugin = this._plugin.name if (this._activeId && !err.id) err.id = this._activeId if (this._activeCode) { err.pluginCode = this._activeCode @@ -740,7 +736,7 @@ class PluginContext implements Omit { if ( this instanceof TransformPluginContext && typeof err.loc?.line === 'number' && - typeof err.loc?.column === 'number' + typeof err.loc.column === 'number' ) { const rawSourceMap = this._getCombinedSourcemap() if (rawSourceMap && 'version' in rawSourceMap) { @@ -749,7 +745,7 @@ class PluginContext implements Omit { line: Number(err.loc.line), column: Number(err.loc.column), }) - if (source && line != null && column != null) { + if (source) { err.loc = { file: source, line, column } } } @@ -851,7 +847,7 @@ class TransformPluginContext } } - _getCombinedSourcemap(): SourceMap { + _getCombinedSourcemap(): SourceMap | { mappings: '' } | null { if ( debugSourcemapCombine && debugSourcemapCombineFilter && @@ -871,7 +867,7 @@ class TransformPluginContext combinedMap.mappings === '' ) { this.sourcemapChain.length = 0 - return combinedMap as SourceMap + return combinedMap } for (let m of this.sourcemapChain) { @@ -912,11 +908,11 @@ class TransformPluginContext this.combinedMap = combinedMap this.sourcemapChain.length = 0 } - return this.combinedMap as SourceMap + return this.combinedMap } getCombinedSourcemap(): SourceMap { - const map = this._getCombinedSourcemap() as SourceMap | { mappings: '' } + const map = this._getCombinedSourcemap() if (!map || (!('version' in map) && map.mappings === '')) { return new MagicString(this.originalCode).generateMap({ includeContent: true, @@ -953,7 +949,7 @@ class PluginContainer { }) { return options?.environment ? options.environment - : this.environments?.[options?.ssr ? 'ssr' : 'client'] + : this.environments[options?.ssr ? 'ssr' : 'client'] } private _getPluginContainer(options?: { diff --git a/packages/vite/src/node/server/transformRequest.ts b/packages/vite/src/node/server/transformRequest.ts index 66e81559bf4aca..a7104753b976a4 100644 --- a/packages/vite/src/node/server/transformRequest.ts +++ b/packages/vite/src/node/server/transformRequest.ts @@ -70,7 +70,7 @@ export function transformRequest( options: TransformOptions = {}, ): Promise { // Backward compatibility when only `ssr` is passed - if (!options?.ssr) { + if (!options.ssr) { // Backward compatibility options = { ...options, ssr: environment.config.consumer === 'server' } } @@ -215,16 +215,18 @@ async function getCachedTransformResult( // tries to handle soft invalidation of the module if available, // returns a boolean true is successful, or false if no handling is needed - const softInvalidatedTransformResult = - module && - (await handleModuleSoftInvalidation(environment, module, timestamp)) + const softInvalidatedTransformResult = await handleModuleSoftInvalidation( + environment, + module, + timestamp, + ) if (softInvalidatedTransformResult) { debugCache?.(`[memory-hmr] ${prettyUrl}`) return softInvalidatedTransformResult } // check if we have a fresh cache - const cached = module?.transformResult + const cached = module.transformResult if (cached) { debugCache?.(`[memory] ${prettyUrl}`) return cached @@ -345,10 +347,7 @@ async function loadAndTransform( inMap: map, }) const originalCode = code - if ( - transformResult == null || - (isObject(transformResult) && transformResult.code == null) - ) { + if (transformResult.code === originalCode) { // no transform applied, keep code as-is debugTransform?.( timeFrom(transformStart) + colors.dim(` [skipped] ${prettyUrl}`), @@ -413,7 +412,7 @@ async function loadAndTransform( ? await ssrTransform(code, normalizedMap, url, originalCode, { json: { stringify: - topLevelConfig.json?.stringify === true && + topLevelConfig.json.stringify === true && topLevelConfig.json.namedExports !== true, }, }) diff --git a/packages/vite/src/node/ssr/ssrStacktrace.ts b/packages/vite/src/node/ssr/ssrStacktrace.ts index 18489224ea4af6..287e0a85f160ff 100644 --- a/packages/vite/src/node/ssr/ssrStacktrace.ts +++ b/packages/vite/src/node/ssr/ssrStacktrace.ts @@ -48,7 +48,7 @@ export function ssrRewriteStacktrace( column: Number(column) - 1, }) - if (!pos.source || pos.line == null || pos.column == null) { + if (!pos.source) { return input } diff --git a/packages/vite/src/node/ssr/ssrTransform.ts b/packages/vite/src/node/ssr/ssrTransform.ts index 3a8aa9a33eeda8..c4552f73229663 100644 --- a/packages/vite/src/node/ssr/ssrTransform.ts +++ b/packages/vite/src/node/ssr/ssrTransform.ts @@ -473,7 +473,7 @@ function walk( } function isInScope(name: string, parents: Node[]) { - return parents.some((node) => node && scopeMap.get(node)?.has(name)) + return parents.some((node) => scopeMap.get(node)?.has(name)) } function handlePattern(p: Pattern, parentScope: _Node) { if (p.type === 'Identifier') { @@ -568,11 +568,11 @@ function walk( return } ;(eswalk as any)(p.type === 'AssignmentPattern' ? p.left : p, { - enter(child: Node, parent: Node) { + enter(child: Node, parent: Node | undefined) { // skip params default value of destructure if ( parent?.type === 'AssignmentPattern' && - parent?.right === child + parent.right === child ) { return this.skip() } @@ -583,8 +583,8 @@ function walk( // assignment of a destructuring variable if ( (parent?.type === 'TemplateLiteral' && - parent?.expressions.includes(child)) || - (parent?.type === 'CallExpression' && parent?.callee === child) + parent.expressions.includes(child)) || + (parent?.type === 'CallExpression' && parent.callee === child) ) { return } @@ -706,10 +706,10 @@ function isRefIdentifier(id: Identifier, parent: _Node, parentStack: _Node[]) { } const isStaticProperty = (node: _Node): node is Property => - node && node.type === 'Property' && !node.computed + node.type === 'Property' && !node.computed -const isStaticPropertyKey = (node: _Node, parent: _Node) => - isStaticProperty(parent) && parent.key === node +const isStaticPropertyKey = (node: _Node, parent: _Node | undefined) => + parent && isStaticProperty(parent) && parent.key === node const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/ function isFunction(node: _Node): node is FunctionNode { @@ -732,10 +732,7 @@ function isInDestructuringAssignment( parent: _Node, parentStack: _Node[], ): boolean { - if ( - parent && - (parent.type === 'Property' || parent.type === 'ArrayPattern') - ) { + if (parent.type === 'Property' || parent.type === 'ArrayPattern') { return parentStack.some((i) => i.type === 'AssignmentExpression') } return false diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index 794a333276782f..233f96810da833 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -987,7 +987,6 @@ export async function resolveServerUrls( .flatMap((nInterface) => nInterface ?? []) .filter( (detail) => - detail && detail.address && (detail.family === 'IPv4' || // @ts-expect-error Node 18.0 - 18.3 returns number @@ -1307,11 +1306,17 @@ export function transformStableResult( } } -export async function asyncFlatten(arr: T[]): Promise { +type AsyncFlatten = T extends (infer U)[] + ? Exclude, U[]>[] + : never + +export async function asyncFlatten( + arr: T, +): Promise> { do { arr = (await Promise.all(arr)).flat(Infinity) as any } while (arr.some((v: any) => v?.then)) - return arr + return arr as unknown[] as AsyncFlatten } // strip UTF-8 BOM @@ -1414,7 +1419,7 @@ export function getNpmPackageName(importPath: string): string | null { } export function getPkgName(name: string): string | undefined { - return name?.[0] === '@' ? name.split('/')[1] : name + return name[0] === '@' ? name.split('/')[1] : name } const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g diff --git a/packages/vite/src/shared/hmr.ts b/packages/vite/src/shared/hmr.ts index 342e0894bef971..a5d7d811566f8c 100644 --- a/packages/vite/src/shared/hmr.ts +++ b/packages/vite/src/shared/hmr.ts @@ -79,7 +79,7 @@ export class HMRContext implements ViteHotContext { // extracted in the server for propagation acceptExports( _: string | readonly string[], - callback: (data: any) => void, + callback?: (data: any) => void, ): void { this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod)) }