Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: simplify some code and reduce diff #17969

Merged
merged 11 commits into from
Aug 29, 2024
4 changes: 2 additions & 2 deletions packages/vite/src/module-runner/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { HotPayload } from 'types/hmrPayload'
import type { HMRConnection, HMRLogger } from '../shared/hmr'
import type {
DefineImportMetadata,
SSRImportBaseMetadata,
SSRImportMetadata,
} from '../shared/ssrTransform'
import type { ModuleCacheMap } from './moduleCache'
import type {
Expand All @@ -17,7 +17,7 @@ import type { DecodedMap } from './sourcemap/decoder'
import type { InterceptorOptions } from './sourcemap/interceptor'
import type { RunnerTransport } from './runnerTransport'

export type { DefineImportMetadata, SSRImportBaseMetadata as SSRImportMetadata }
export type { DefineImportMetadata, SSRImportMetadata }

export interface ModuleRunnerHMRConnection extends HMRConnection {
/**
Expand Down
1 change: 0 additions & 1 deletion packages/vite/src/module-runner/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ function encodePathChars(filepath: string) {

export const posixDirname = pathe.dirname
export const posixResolve = pathe.resolve
export const normalizeString = pathe.normalizeString

export function posixPathToFileHref(posixPath: string): string {
let resolved = posixResolve(posixPath)
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/baseEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export class PartialEnvironment {
)
const environment = colors.dim(`(${this.name})`)
const colorIndex =
[...environment].reduce((acc, c) => acc + c.charCodeAt(0), 0) %
[...this.name].reduce((acc, c) => acc + c.charCodeAt(0), 0) %
environmentColors.length
const infoColor = environmentColors[colorIndex || 0]
this.logger = {
Expand Down
13 changes: 6 additions & 7 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ import { createIdResolver } from '../idResolver'
import type { ResolveIdFn } from '../idResolver'
import { PartialEnvironment } from '../baseEnvironment'
import type { TransformPluginContext } from '../server/pluginContainer'
import type { DevEnvironment } from '..'
import { addToHTMLProxyTransformResult } from './html'
import {
assetUrlRE,
Expand Down Expand Up @@ -972,10 +973,8 @@ export function cssAnalysisPlugin(config: ResolvedConfig): Plugin {
return
}

const environment = this.environment
const moduleGraph =
environment.mode === 'dev' ? environment.moduleGraph : undefined
const thisModule = moduleGraph?.getModuleById(id)
const { moduleGraph } = this.environment as DevEnvironment
const thisModule = moduleGraph.getModuleById(id)

// Handle CSS @import dependency HMR and other added modules via this.addWatchFile.
// JS-related HMR is handled in the import-analysis plugin.
Expand All @@ -995,13 +994,13 @@ export function cssAnalysisPlugin(config: ResolvedConfig): Plugin {
for (const file of pluginImports) {
depModules.add(
isCSSRequest(file)
? moduleGraph!.createFileOnlyEntry(file)
: await moduleGraph!.ensureEntryFromUrl(
? moduleGraph.createFileOnlyEntry(file)
: await moduleGraph.ensureEntryFromUrl(
fileToDevUrl(file, config, /* skipBase */ true),
),
)
}
moduleGraph!.updateModuleInfo(
moduleGraph.updateModuleInfo(
thisModule,
depModules,
null,
Expand Down
8 changes: 4 additions & 4 deletions packages/vite/src/node/plugins/esbuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ export const defaultEsbuildSupported = {
'import-meta': true,
}

// TODO: rework to avoid caching the server for this module.
// If two servers are created in the same process, they will interfere with each other.
let server: ViteDevServer

export interface ESBuildOptions extends TransformOptions {
include?: string | RegExp | string[] | RegExp[]
exclude?: string | RegExp | string[] | RegExp[]
Expand Down Expand Up @@ -74,10 +78,6 @@ type TSConfigJSON = {
}
type TSCompilerOptions = NonNullable<TSConfigJSON['compilerOptions']>

// TODO: rework to avoid caching the server for this module.
// If two servers are created in the same process, they will interfere with each other.
let server: ViteDevServer

export async function transformWithEsbuild(
code: string,
filename: string,
Expand Down
8 changes: 3 additions & 5 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,8 +329,6 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {

async transform(html, id) {
if (id.endsWith('.html')) {
const { modulePreload } = this.environment.config.build

id = normalizePath(id)
const relativeUrlPath = normalizePath(path.relative(config.root, id))
const publicPath = `/${relativeUrlPath}`
Expand Down Expand Up @@ -676,6 +674,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
processedHtml.set(id, s.toString())

// inject module preload polyfill only when configured and needed
const { modulePreload } = this.environment.config.build
if (
modulePreload !== false &&
modulePreload.polyfill &&
Expand All @@ -691,8 +690,6 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
},

async generateBundle(options, bundle) {
const { modulePreload } = this.environment.config.build

const analyzedChunk: Map<OutputChunk, number> = new Map()
const inlineEntryChunk = new Set<string>()
const getImportedChunks = (
Expand Down Expand Up @@ -840,6 +837,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
toScriptTag(chunk, toOutputAssetFilePath, isAsync),
)
} else {
const { modulePreload } = this.environment.config.build
assetTags = [toScriptTag(chunk, toOutputAssetFilePath, isAsync)]
if (modulePreload !== false) {
const resolveDependencies =
Expand All @@ -865,7 +863,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
}

// inject css link when cssCodeSplit is false
if (this.environment.config.build.cssCodeSplit === false) {
if (!this.environment.config.build.cssCodeSplit) {
const cssChunk = Object.values(bundle).find(
(chunk) => chunk.type === 'asset' && chunk.name === 'style.css',
) as OutputAsset | undefined
Expand Down
13 changes: 5 additions & 8 deletions packages/vite/src/node/plugins/importAnalysisBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,8 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
},

load(id) {
const { environment } = this
if (environment && id === preloadHelperId) {
const { modulePreload } = environment.config.build
if (id === preloadHelperId) {
const { modulePreload } = this.environment.config.build

const scriptRel =
modulePreload && modulePreload.polyfill
Expand Down Expand Up @@ -209,7 +208,6 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
},

async transform(source, importer) {
const { environment } = this
if (isInNodeModules(importer) && !dynamicImportPrefixRE.test(source)) {
return
}
Expand Down Expand Up @@ -361,7 +359,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
if (s) {
return {
code: s.toString(),
map: environment.config.build.sourcemap
map: this.environment.config.build.sourcemap
? s.generateMap({ hires: 'boundary' })
: null,
}
Expand All @@ -370,11 +368,10 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {

renderChunk(code, _, { format }) {
// make sure we only perform the preload logic in modern builds.
const { environment } = this
if (environment && code.indexOf(isModernFlag) > -1) {
if (code.indexOf(isModernFlag) > -1) {
const re = new RegExp(isModernFlag, 'g')
const isModern = String(format === 'es')
if (environment.config.build.sourcemap) {
if (this.environment.config.build.sourcemap) {
const s = new MagicString(code)
let match: RegExpExecArray | null
while ((match = re.exec(code))) {
Expand Down
1 change: 0 additions & 1 deletion packages/vite/src/node/plugins/preAlias.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ export function preAliasPlugin(config: ResolvedConfig): Plugin {
const depsOptimizer =
environment.mode === 'dev' ? environment.depsOptimizer : undefined
if (
environment &&
importer &&
depsOptimizer &&
bareImportRE.test(id) &&
Expand Down
14 changes: 7 additions & 7 deletions packages/vite/src/node/server/hmr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,16 +272,16 @@ export async function handleHMRUpdate(
// Invalidate the hmrContext to force compat modules to be updated
mixedHmrContext.modules = mixedHmrContext.modules.filter(
(mixedMod) =>
filteredModules.find((mod) => mixedMod.id === mod.id) ||
ssrHotUpdateOptions?.modules.find(
filteredModules.some((mod) => mixedMod.id === mod.id) ||
ssrHotUpdateOptions?.modules.some(
(ssrMod) => ssrMod.id === mixedMod.id,
),
)
mixedHmrContext.modules.push(
...filteredModules
.filter(
(mod) =>
!mixedHmrContext.modules.find(
!mixedHmrContext.modules.some(
(mixedMod) => mixedMod.id === mod.id,
),
)
Expand All @@ -306,13 +306,13 @@ export async function handleHMRUpdate(
mixedHmrContext.modules = filteredModules
clientHotUpdateOptions.modules =
clientHotUpdateOptions.modules.filter((mod) =>
filteredModules.find((mixedMod) => mod.id === mixedMod.id),
filteredModules.some((mixedMod) => mod.id === mixedMod.id),
)
clientHotUpdateOptions.modules.push(
...(filteredModules
.filter(
(mixedMod) =>
!clientHotUpdateOptions.modules.find(
!clientHotUpdateOptions.modules.some(
(mod) => mod.id === mixedMod.id,
),
)
Expand All @@ -322,13 +322,13 @@ export async function handleHMRUpdate(
if (ssrHotUpdateOptions) {
ssrHotUpdateOptions.modules = ssrHotUpdateOptions.modules.filter(
(mod) =>
filteredModules.find((mixedMod) => mod.id === mixedMod.id),
filteredModules.some((mixedMod) => mod.id === mixedMod.id),
)
ssrHotUpdateOptions.modules.push(
...(filteredModules
.filter(
(mixedMod) =>
!ssrHotUpdateOptions.modules.find(
!ssrHotUpdateOptions.modules.some(
(mod) => mod.id === mixedMod.id,
),
)
Expand Down
24 changes: 13 additions & 11 deletions packages/vite/src/node/ssr/ssrModuleLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,21 @@ export async function ssrLoadModule(
server: ViteDevServer,
fixStacktrace?: boolean,
): Promise<SSRModule> {
const runner =
server._ssrCompatModuleRunner ||
(server._ssrCompatModuleRunner = createServerModuleRunner(
server.environments.ssr,
{
sourcemapInterceptor: false,
hmr: false,
},
))

server._ssrCompatModuleRunner ||= createServerModuleRunner(
server.environments.ssr,
{
sourcemapInterceptor: false,
hmr: false,
},
)
url = unwrapId(url)

return instantiateModule(url, runner, server, fixStacktrace)
return instantiateModule(
url,
server._ssrCompatModuleRunner,
server,
fixStacktrace,
)
}

async function instantiateModule(
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/shared/ssrTransform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export interface DefineImportMetadata {
importedNames?: string[]
}

export interface SSRImportBaseMetadata extends DefineImportMetadata {
export interface SSRImportMetadata extends DefineImportMetadata {
isDynamicImport?: boolean
}

Expand All @@ -24,7 +24,7 @@ export function analyzeImportedModDifference(
mod: any,
rawId: string,
moduleType: string | undefined,
metadata?: SSRImportBaseMetadata,
metadata?: SSRImportMetadata,
): void {
// No normalization needed if the user already dynamic imports this module
if (metadata?.isDynamicImport) return
Expand Down