@@ -2,12 +2,11 @@ import path from 'node:path'
22
33import { 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
77import 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
1211const PLUGIN_NAME = 'TaroAsyncSubPackagePlugin'
1312const 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 */
209208export 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