Skip to content

Commit 94df184

Browse files
committed
refactor(runner): extract shared bundler layer into @tarojs/runner-utils
1 parent 6c1bd52 commit 94df184

52 files changed

Lines changed: 5129 additions & 4185 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎packages/babel-preset-taro/tests/async-subpackage.spec.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import path from 'node:path'
44
import { transformSync } from '@babel/core'
55
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
66

7-
import AsyncSubPackagePlugin from '../../taro-webpack5-runner/src/plugins/AsyncSubPackagePlugin'
7+
import AsyncSubPackagePlugin from '../../taro-runner-utils/src/bundler/asyncSubPackagePlugin'
88
import MiniPlugin from '../../taro-webpack5-runner/src/plugins/MiniPlugin'
99

1010
const runnerRequire = createRequire(path.resolve(__dirname, '../../taro-webpack5-runner/package.json'))

‎packages/taro-runner-utils/package.json‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,28 @@
66
"license": "MIT",
77
"main": "dist/index.js",
88
"types": "dist/index.d.ts",
9+
"exports": {
10+
".": {
11+
"types": "./dist/index.d.ts",
12+
"default": "./dist/index.js"
13+
},
14+
"./bundler/*.js": {
15+
"types": "./dist/bundler/*.d.ts",
16+
"default": "./dist/bundler/*.js"
17+
},
18+
"./bundler/*": {
19+
"types": "./dist/bundler/*.d.ts",
20+
"default": "./dist/bundler/*.js"
21+
},
22+
"./package.json": "./package.json"
23+
},
24+
"typesVersions": {
25+
"*": {
26+
"bundler/*": [
27+
"./dist/bundler/*.d.ts"
28+
]
29+
}
30+
},
931
"files": [
1032
"dist"
1133
],
@@ -38,6 +60,7 @@
3860
"@types/sax": "^1.2.4",
3961
"autoprefixer": "^10.4.19",
4062
"detect-port": "^1.5.1",
63+
"html-minifier": "^4.0.0",
4164
"jsdom": "^24.0.0",
4265
"loader-utils": "^3.2.1",
4366
"miniprogram-simulate": "^1.6.1",
@@ -50,12 +73,14 @@
5073
"postcss-pxtransform": "workspace:*",
5174
"postcss-url": "^10.1.3",
5275
"sax": "1.2.4",
76+
"tapable": "^2.2.1",
5377
"vm2": "^3.9.19",
5478
"webpack-format-messages": "^3.0.1"
5579
},
5680
"peerDependencies": {
5781
"autoprefixer": "^10.4.19",
5882
"detect-port": "^1.5.1",
83+
"html-minifier": "^4.0.0",
5984
"jsdom": "^24.0.0",
6085
"loader-utils": "^3.2.1",
6186
"miniprogram-simulate": "^1.6.1",
@@ -68,6 +93,7 @@
6893
"postcss-pxtransform": "workspace:*",
6994
"postcss-url": "^10.1.3",
7095
"sax": "1.2.4",
96+
"tapable": "^2.2.1",
7197
"vm2": "^3.9.19",
7298
"webpack-format-messages": "^3.0.1"
7399
},
@@ -78,6 +104,9 @@
78104
"detect-port": {
79105
"optional": true
80106
},
107+
"html-minifier": {
108+
"optional": true
109+
},
81110
"jsdom": {
82111
"optional": true
83112
},
@@ -114,6 +143,9 @@
114143
"sax": {
115144
"optional": true
116145
},
146+
"tapable": {
147+
"optional": true
148+
},
117149
"vm2": {
118150
"optional": true
119151
},

packages/taro-webpack5-runner/src/utils/asyncSubPackage.ts renamed to packages/taro-runner-utils/src/bundler/asyncSubPackage.ts

File renamed without changes.

packages/taro-webpack5-runner/src/plugins/AsyncSubPackagePlugin.ts renamed to packages/taro-runner-utils/src/bundler/asyncSubPackagePlugin.ts

Lines changed: 43 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@ import path from 'node:path'
22

33
import { REG_SCRIPTS, REG_STYLE } from '@tarojs/helper'
44

5-
import { createAsyncCommonChunkName, getAsyncRootAssetNames, getAsyncRootForModule, getSingleAsyncRootForModules, getSourceRootForResource, normalizePathForAsyncSubPackage } from '../utils/asyncSubPackage'
5+
import { createAsyncCommonChunkName, getAsyncRootAssetNames, getAsyncRootForModule, getSingleAsyncRootForModules, getSourceRootForResource, normalizePathForAsyncSubPackage } from './asyncSubPackage'
66

77
import type { SubPackage } from '@tarojs/taro'
8-
import type { Compiler } from 'webpack'
9-
import type TaroMiniPlugin from './MiniPlugin'
10-
import type { AsyncSubPackageRuntimeRoot } from './SubPackageIndiePlugin'
8+
import type { BaseMiniPlugin } from './miniPlugin'
9+
import type { AsyncSubPackageRuntimeRoot } from './subPackageIndiePlugin'
1110

1211
const PLUGIN_NAME = 'TaroAsyncSubPackagePlugin'
1312
const ASYNC_SUBPACKAGE_ENTRY = 'index'
@@ -203,20 +202,21 @@ function createMiniAsyncSubPackageRuntimeModuleClass (
203202
/**
204203
* 异步分包插件:集中处理 asyncSubPackage 的 chunk 归属、运行时加载补丁、异步分包入口和 app.json 注册。
205204
*
206-
* 当前方案保留 webpack 原生 import(),让 webpack 继续生成异步 chunk;随后在产物阶段把这些 chunk
205+
* 当前方案保留原生 import(),让打包器继续生成异步 chunk;随后在产物阶段把这些 chunk
207206
* 移到配置的 asyncRoot 下,并生成微信可识别的 asyncRoot/index 占位页面作为分包加载入口。
208207
*/
209208
export default class AsyncSubPackagePlugin {
210-
miniPlugin: TaroMiniPlugin
209+
miniPlugin: BaseMiniPlugin<any, any>
211210
asyncRootMap: Map<string, string> = new Map()
212211
asyncRuntimeRoots: AsyncSubPackageRuntimeRoot[] = []
213-
private appliedCompilers: WeakSet<Compiler> = new WeakSet()
212+
private appliedCompilers: WeakSet<object> = new WeakSet()
213+
private lastCompiler: any = null
214214
private miniHooksApplied = false
215215
private asyncModuleCache = new WeakMap<any, string | null | undefined>()
216216
private asyncChunkRootCache = new WeakMap<any, string | null>()
217217
private asyncChunkSourceRoots = new Map<string, Set<string>>()
218218

219-
constructor (miniPlugin: TaroMiniPlugin, asyncRootMap?: Map<string, string>) {
219+
constructor (miniPlugin: BaseMiniPlugin<any, any>, asyncRootMap?: Map<string, string>) {
220220
this.miniPlugin = miniPlugin
221221
if (asyncRootMap) {
222222
this.updateAsyncRootMap(asyncRootMap)
@@ -232,7 +232,11 @@ export default class AsyncSubPackagePlugin {
232232
this.asyncRuntimeRoots = asyncRuntimeRoots.map(item => ({ ...item }))
233233
}
234234

235-
apply (compiler?: Compiler) {
235+
apply (compiler?: any) {
236+
if (compiler) {
237+
this.lastCompiler = compiler
238+
}
239+
236240
if (compiler && !this.appliedCompilers.has(compiler)) {
237241
this.appliedCompilers.add(compiler)
238242
compiler.hooks.compilation.tap(PLUGIN_NAME, () => {
@@ -253,11 +257,11 @@ export default class AsyncSubPackagePlugin {
253257
}
254258
}
255259

256-
private setupAsyncBabel (compiler: Compiler) {
257-
compiler.hooks.compilation.tap(PLUGIN_NAME, (_compilation, { normalModuleFactory }) => {
258-
normalModuleFactory.hooks.afterResolve.tap(PLUGIN_NAME, data => {
260+
private setupAsyncBabel (compiler: any) {
261+
compiler.hooks.compilation.tap(PLUGIN_NAME, (_compilation: any, { normalModuleFactory }: any) => {
262+
normalModuleFactory.hooks.afterResolve.tap(PLUGIN_NAME, (data: any) => {
259263
if (this.asyncRootMap.size === 0) return
260-
const { loaders } = data.createData
264+
const loaders = data.createData?.loaders
261265
if (!loaders) return
262266

263267
let stamped = false
@@ -288,7 +292,7 @@ export default class AsyncSubPackagePlugin {
288292
// 两种 Babel 模式(保留 import() vs 转换为 require())会相互污染。
289293
// 按 loaderToIdent 的序列化规则重算 request,使异步模式获得独立 identifier。
290294
data.createData.request = `${loaders
291-
.map(loader => {
295+
.map((loader: any) => {
292296
if (loader.options && typeof loader.options === 'object' && loader.ident) {
293297
return `${loader.loader}??${loader.ident}`
294298
}
@@ -304,7 +308,7 @@ export default class AsyncSubPackagePlugin {
304308

305309
// ==================== Async SplitChunks ====================
306310

307-
private setupAsyncSplitChunks (compiler: Compiler) {
311+
private setupAsyncSplitChunks (compiler: any) {
308312
const splitChunks = compiler.options.optimization?.splitChunks
309313
if (!splitChunks) return
310314

@@ -401,15 +405,17 @@ export default class AsyncSubPackagePlugin {
401405
return sourceRoots
402406
}
403407

404-
private setupAsyncChunkOptimization (compiler: Compiler) {
408+
private setupAsyncChunkOptimization (compiler: any) {
405409
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation: any) => {
406-
compilation.hooks.optimizeChunks.tap(PLUGIN_NAME, chunks => {
410+
if (!compilation.hooks.optimizeChunks) return
411+
412+
compilation.hooks.optimizeChunks.tap(PLUGIN_NAME, (chunks: any) => {
407413
if (this.asyncRootMap.size === 0) return
408414

409415
for (const chunk of chunks) {
410416
// 入口 chunk 名要在 app.json/页面注册中保持稳定,不能被改成 asyncRoot 路径。
411417
if (chunk.hasRuntime?.() || chunk.canBeInitial?.()) continue
412-
const modules = Array.from(compilation.chunkGraph.getChunkModulesIterable(chunk))
418+
const modules = Array.from(compilation.chunkGraph.getChunkModulesIterable(chunk)) as any[]
413419
const jsModules = modules.filter(module => isJavaScriptModule(module))
414420
if (jsModules.length === 0) continue
415421

@@ -445,14 +451,15 @@ export default class AsyncSubPackagePlugin {
445451

446452
// ==================== Async Chunk Runtime ====================
447453

448-
private setupAsyncChunkRuntime (compiler: Compiler) {
454+
private setupAsyncChunkRuntime (compiler: any) {
449455
const webpack = compiler.webpack as any
456+
if (!webpack) return
450457
const { RuntimeGlobals, RuntimeModule, Template } = webpack
451458
const loadScript = RuntimeGlobals?.loadScript
452459
const ensureChunkHandlers = RuntimeGlobals?.ensureChunkHandlers
453460
const getChunkScriptFilename = RuntimeGlobals?.getChunkScriptFilename
454461
const publicPath = RuntimeGlobals?.publicPath
455-
if (!loadScript || !ensureChunkHandlers || !getChunkScriptFilename || !publicPath || !RuntimeModule) return
462+
if (!loadScript || !ensureChunkHandlers || !getChunkScriptFilename || !publicPath || !RuntimeModule || !Template) return
456463

457464
const MiniAsyncSubPackageRuntimeModule = createMiniAsyncSubPackageRuntimeModuleClass(
458465
webpack,
@@ -461,6 +468,8 @@ export default class AsyncSubPackagePlugin {
461468
)
462469

463470
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation: any) => {
471+
if (!compilation.hooks.runtimeRequirementInTree) return
472+
464473
const runtimeAppliedChunks = new WeakSet<any>()
465474
const addMiniAsyncRuntimeModule = (chunk: any) => {
466475
if (this.asyncRootMap.size === 0 || runtimeAppliedChunks.has(chunk)) return
@@ -470,7 +479,7 @@ export default class AsyncSubPackagePlugin {
470479
}
471480

472481
// 不依赖 runtime.js 文本格式,也不只依赖某一个 runtime requirement:
473-
// dev/prod 下 webpack 可能通过不同 requirement 触发异步 chunk runtime。
482+
// dev/prod 下打包器可能通过不同 requirement 触发异步 chunk runtime。
474483
compilation.hooks.runtimeRequirementInTree.for(loadScript).tap(PLUGIN_NAME, addMiniAsyncRuntimeModule)
475484
compilation.hooks.runtimeRequirementInTree.for(ensureChunkHandlers).tap(PLUGIN_NAME, addMiniAsyncRuntimeModule)
476485
compilation.hooks.runtimeRequirementInTree.for(getChunkScriptFilename).tap(PLUGIN_NAME, addMiniAsyncRuntimeModule)
@@ -479,15 +488,19 @@ export default class AsyncSubPackagePlugin {
479488

480489
// ==================== Async Chunk Asset Extraction ====================
481490

482-
private setupAsyncChunkAssetExtraction (compiler: Compiler) {
491+
private setupAsyncChunkAssetExtraction (compiler: any) {
483492
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation: any) => {
484493
// PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER 在 webpack 5 中为 300;fallback 仅保留极旧版本兼容。
485-
const stage = (compilation.constructor as any).PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER ?? 300
494+
const stage = compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER ??
495+
(compilation.constructor as any)?.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER ??
496+
300
486497
compilation.hooks.processAssets.tap(
487498
{ name: PLUGIN_NAME, stage },
488499
() => {
489500
if (this.asyncRootMap.size === 0) return
490-
const { RawSource } = compilation.compiler.webpack.sources
501+
const sources = compilation.compiler?.webpack?.sources || compiler.webpack?.sources || this.miniPlugin.getSources?.()
502+
if (!sources?.RawSource) return
503+
const { RawSource } = sources
491504
this.moveAsyncRootStylesToSourceRoots(compilation, RawSource)
492505
this.moveAsyncRootTemplatesToSourceRoots(compilation)
493506
this.createAsyncRootEntries(compilation, RawSource)
@@ -509,8 +522,8 @@ export default class AsyncSubPackagePlugin {
509522
if (jsAssets.length === 0) continue
510523

511524
// 微信 require.async 只能稳定加载 app.json 中注册过的分包页面入口。
512-
// 因此 asyncRoot 只注册 index 页面,index.js 再同步 require 真实 webpack async chunk,
513-
// 让 webpack JSONP runtime 完成 chunk 注册。
525+
// 因此 asyncRoot 只注册 index 页面,index.js 再同步 require 真实异步 chunk,
526+
// 让运行时完成 chunk 注册。
514527
const requires = jsAssets
515528
.map(assetName => `require('./${path.posix.basename(assetName)}')`)
516529
.join('\n')
@@ -574,13 +587,15 @@ export default class AsyncSubPackagePlugin {
574587
private setupSubPackageRegistration () {
575588
this.miniPlugin.hooks.afterGenerateFiles.tap(PLUGIN_NAME, (compilation: any) => {
576589
if (this.asyncRootMap.size === 0) return
577-
const { RawSource } = (compilation.compiler?.webpack?.sources || require('webpack').sources) as any
590+
const sources = compilation.compiler?.webpack?.sources || this.lastCompiler?.webpack?.sources || this.miniPlugin.getSources?.()
591+
if (!sources?.RawSource) return
592+
const { RawSource } = sources
578593

579594
const appConfig = this.miniPlugin.appConfig
580595
const exist = (appConfig as any).subPackages || (appConfig as any).subpackages || []
581596
const news: SubPackage[] = []
582597
// 多个 sourceRoot 可以指向同一个 asyncRoot,app.json 中只能注册一次。
583-
// pages 固定为 index,避免把每个 webpack chunk 当成小程序页面。
598+
// pages 固定为 index,避免把每个异步 chunk 当成小程序页面。
584599
const asyncRoots = new Set(this.asyncRootMap.values())
585600
for (const asyncRoot of asyncRoots) {
586601
news.push({ root: asyncRoot, pages: [ASYNC_SUBPACKAGE_ENTRY], independent: false })

0 commit comments

Comments
 (0)