Skip to content

Commit 459ba1c

Browse files
authored
perf(vite): 跳过 Generic Web 生产候选状态 (#1140)
* perf(vite): 跳过 Generic Web 生产候选状态 Refs #1107 * chore(ci): keep vite runtime within line limit Refs #1107
1 parent 28f4984 commit 459ba1c

5 files changed

Lines changed: 53 additions & 3 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"weapp-tailwindcss": patch
3+
---
4+
5+
优化 Generic Web 非 watch 生产构建:跳过不需要的小程序 source-candidates 状态维护,减少重复扫描与构建生命周期开销。

packages/weapp-tailwindcss/src/bundlers/vite/shared/create-framework-plugins-runtime.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ import { collectConfiguredCssEntries, inferPlatformFromOutDir, isInternalUserDef
6363
import { createFrameworkSourceCandidatesPlugin } from './framework-source-candidates-plugin'
6464
import { createFrameworkSourceScanSession, syncFrameworkSourceCandidatesForHotUpdate } from './framework-source-scan-session'
6565
import { createFrameworkTailwindRootCss } from './framework-tailwind-root-css'
66-
import { createGenericWebProductionBundleHooks, createGenericWebProductionSourceCandidatesApply } from './generic-web-production-fast-path'
66+
import { createGenericWebProductionBundleHooks, createGenericWebProductionSourceCandidatesApply, shouldSkipGenericWebProductionSourceCandidates } from './generic-web-production-fast-path'
6767

6868
const debug = createDebug()
6969
const weappTailwindcssPackageDir = resolvePackageDir('weapp-tailwindcss'); const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir); const generatorPlaceholderCssFile = path.join(weappTailwindcssPackageDir, 'generator-placeholder.css'); const ENV_PLATFORM_KEYS = ['UNI_PLATFORM', 'UNI_UTS_PLATFORM', 'TARO_ENV', 'MPX_CURRENT_TARGET_MODE', 'MPX_CLI_MODE']
@@ -231,6 +231,7 @@ function createViteFrameworkPlugins(options = {}, frameworkBranch): any {
231231
const getSourceCandidateSourcesForEntries = (entries, options2) => sourceCandidateCollector.sourcesForEntries(entries, options2)
232232
const isWatchBuild = () => resolvedConfig?.command === 'build' && resolvedConfig.build.watch != null
233233
const isWatchLikeBuild = () => isWatchBuild() || resolvedConfig?.command === 'serve' || process.env['WEAPP_TW_WATCH_REGRESSION'] === '1' || process.env['WEAPP_TW_HMR_TIMING'] === '1'
234+
const shouldSkipSourceCandidateState = () => shouldSkipGenericWebProductionSourceCandidates({ command: resolvedConfig?.command, frameworkName: frameworkBranch.frameworkName, isWebGeneratorTarget: resolveCurrentGeneratorBranch().isWeb, requiresSourceCandidateState: isCssSourceTraceEnabled(opts), watch: resolvedConfig?.build?.watch })
234235
const isCurrentWebLikeStylePlatform = () => { const platform = resolveViteStylePlatform(); return platform ? isWebOrNativeAppPlatform(platform) : resolveCurrentGeneratorBranch().isWeb }
235236
const normalizeGeneratedCssCacheFile = file => normalizeVitePersistentCacheKey(cleanUrl(file))
236237
const hmrCandidateState = createViteHmrCandidateState({
@@ -451,6 +452,7 @@ ${tracedCss}`
451452
resolveViteStylePlatform, runtimeState, shouldOwnTailwindGeneration, sourceCandidateCollector, sourceScanSession,
452453
tailwindRootCssModuleIds, transformEarlyMiniProgramCss, viteProcessedCssSourceFiles: processedCssRegistry.sourceFiles,
453454
collectSourceCandidates: capability.sourceCandidates,
455+
shouldSkipSourceCandidateState,
454456
}, createGenericWebProductionSourceCandidatesApply({ frameworkName: frameworkBranch.frameworkName, getIsWebGeneratorTarget: () => resolveCurrentGeneratorBranch().isWeb, requiresSourceCandidateState: isCssSourceTraceEnabled(opts) }))
455457
/* eslint-enable antfu/consistent-list-newline */
456458
const postPlugin = createFrameworkPostPlugin({

packages/weapp-tailwindcss/src/bundlers/vite/shared/framework-source-candidates-plugin.ts

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { isSourceCandidateRequest } from '../source-candidates'
1212
import { cleanUrl, isCSSRequest } from '../utils'
1313

1414
export function createFrameworkSourceCandidatesPlugin(options: any, apply?: Plugin['apply']): Plugin {
15+
const shouldSkipSourceCandidateState = () => options.shouldSkipSourceCandidateState?.() === true
1516
const hasDifferentHotModules = (left: ModuleNode[], right: ModuleNode[]) => left.length !== right.length
1617
|| left.some((mod, index) => mod !== right[index])
1718
const hasTemplateHotSourceModule = (modules: Array<{ id?: string | null, url?: string | null }>) => modules.some((mod) => {
@@ -51,6 +52,7 @@ export function createFrameworkSourceCandidatesPlugin(options: any, apply?: Plug
5152
async load(id) {
5253
if (
5354
!options.shouldOwnTailwindGeneration
55+
|| shouldSkipSourceCandidateState()
5456
|| options.isWebOrNativeAppPlatform(options.resolveViteStylePlatform())
5557
|| !isCSSRequest(id)
5658
|| !shouldCollectTransformedSourceCandidates(id)
@@ -73,6 +75,9 @@ export function createFrameworkSourceCandidatesPlugin(options: any, apply?: Plug
7375
transform: {
7476
order: 'pre',
7577
async handler(code, id) {
78+
if (shouldSkipSourceCandidateState()) {
79+
return
80+
}
7681
if (options.hasUserCssLayerBlocks(code)) {
7782
options.rememberOriginalCssLayerSource(id, code)
7883
}
@@ -87,7 +92,7 @@ export function createFrameworkSourceCandidatesPlugin(options: any, apply?: Plug
8792
options.rememberTailwindRootCssModule(id)
8893
}
8994
}
90-
if (!options.shouldOwnTailwindGeneration || options.collectSourceCandidates === false || !isSourceCandidateRequest(id) || !shouldCollectTransformedSourceCandidates(id)) {
95+
if (!options.shouldOwnTailwindGeneration || shouldSkipSourceCandidateState() || options.collectSourceCandidates === false || !isSourceCandidateRequest(id) || !shouldCollectTransformedSourceCandidates(id)) {
9196
return shouldReturnTransformedCode ? { code: transformedCode, map: null } : undefined
9297
}
9398
return options.hmrTimingRecorder.measure('sourceCandidates.transform', async () => {
@@ -105,6 +110,9 @@ export function createFrameworkSourceCandidatesPlugin(options: any, apply?: Plug
105110
},
106111
},
107112
async watchChange(id, change) {
113+
if (shouldSkipSourceCandidateState()) {
114+
return
115+
}
108116
recordCompilationDependencyChanges(options.runtimeState, createCompilationDependencyChanges([path.resolve(cleanUrl(id))]))
109117
await options.hmrTimingRecorder.measure('sourceCandidates.watchChange', async () => {
110118
if (options.shouldOwnTailwindGeneration && options.collectSourceCandidates !== false && isSourceCandidateRequest(id)) {
@@ -147,6 +155,9 @@ export function createFrameworkSourceCandidatesPlugin(options: any, apply?: Plug
147155
handleHotUpdate: {
148156
order: 'post',
149157
async handler(ctx) {
158+
if (shouldSkipSourceCandidateState()) {
159+
return
160+
}
150161
recordCompilationDependencyChanges(options.runtimeState, createCompilationDependencyChanges([path.resolve(cleanUrl(ctx.file))]))
151162
return options.hmrTimingRecorder.measure('sourceCandidates.handleHotUpdate', async () => {
152163
const isSourceCandidateHotUpdate = options.shouldOwnTailwindGeneration && options.collectSourceCandidates !== false && isSourceCandidateRequest(ctx.file)
@@ -307,8 +318,16 @@ export function createFrameworkSourceCandidatesPlugin(options: any, apply?: Plug
307318
options.hmrCssModuleVersions?.clear()
308319
},
309320
async buildStart() {
321+
if (shouldSkipSourceCandidateState()) {
322+
return
323+
}
310324
await options.hmrTimingRecorder.measure('sourceCandidates.buildStart', options.prepareTailwindGeneration, { emit: false })
311325
},
312-
generateBundle: options.preGenerateBundleHook,
326+
async generateBundle(...args: any[]) {
327+
if (shouldSkipSourceCandidateState()) {
328+
return
329+
}
330+
return options.preGenerateBundleHook?.apply(this, args)
331+
},
313332
}
314333
}

packages/weapp-tailwindcss/test/bundlers/vite-dispatcher.unit.test.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ describe('vite 单入口 dispatcher', () => {
1515
setCurrentContext(context)
1616
const { WeappTailwindcss } = await import('@/bundlers/vite')
1717
const plugins = WeappTailwindcss()
18+
const sourceCandidates = findPlugin(plugins, ':source-candidates')!
19+
expect(sourceCandidates.apply).toBeTypeOf('function')
20+
expect(typeof sourceCandidates.apply === 'function' && sourceCandidates.apply({ build: {} }, { command: 'build', mode: 'production' })).toBe(true)
1821
const post = findPlugin(plugins, ':post')!
1922
await post.configResolved?.call(post, {
2023
command: 'build',
@@ -24,6 +27,7 @@ describe('vite 单入口 dispatcher', () => {
2427
} as ResolvedConfig)
2528

2629
expect(context.generator).toMatchObject({ target: 'web' })
30+
expect(typeof sourceCandidates.apply === 'function' && sourceCandidates.apply({ build: {} }, { command: 'build', mode: 'production' })).toBe(false)
2731
const js = findPlugin(plugins, ':js:serve')
2832
const jsResult = await js?.transform?.call(js, 'const cls = "text-red-500"', '/project/main.ts')
2933
expect(jsResult).toBeUndefined()

packages/weapp-tailwindcss/test/bundlers/vite-source-candidates-hmr.unit.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,26 @@ function getTransformHandler(plugin: ReturnType<typeof createFrameworkSourceCand
1313
}
1414

1515
describe('Vite source candidate HMR transactions', () => {
16+
it('skips source candidate lifecycle work after Generic Web production profile resolves', async () => {
17+
const prepareTailwindGeneration = vi.fn()
18+
const preGenerateBundleHook = vi.fn()
19+
const plugin = createFrameworkSourceCandidatesPlugin({
20+
hmrTimingRecorder: { measure: (_name: string, task: () => unknown) => task() },
21+
preGenerateBundleHook,
22+
prepareTailwindGeneration,
23+
shouldSkipSourceCandidateState: () => true,
24+
})
25+
26+
await plugin.buildStart?.call(plugin)
27+
await plugin.generateBundle?.call(plugin, {}, {})
28+
await expect(getTransformHandler(plugin)?.call(plugin, 'const cls = "text-red-500"', '/project/src/page.ts')).resolves.toBeUndefined()
29+
await plugin.watchChange?.('/project/src/page.ts', { event: 'update' } as any)
30+
await getHandleHotUpdateHandler(plugin)?.call(plugin, { file: '/project/src/page.ts' } as any)
31+
32+
expect(prepareTailwindGeneration).not.toHaveBeenCalled()
33+
expect(preGenerateBundleHook).not.toHaveBeenCalled()
34+
})
35+
1636
it('keeps weapp-vite sidecar requests out of source candidate memory', async () => {
1737
const rememberKnownSfcSource = vi.fn()
1838
const rememberTailwindRootCssModule = vi.fn()

0 commit comments

Comments
 (0)