@tarojs/webpack5-runner 4.1.12-beta.3 → 4.1.12-beta.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -25,8 +25,13 @@ const TaroNormalModulesPlugin_1 = __importDefault(require("./TaroNormalModulesPl
25
25
  const TaroSingleEntryPlugin_1 = __importDefault(require("./TaroSingleEntryPlugin"));
26
26
  const baseCompName = 'comp';
27
27
  const customWrapperName = 'custom-wrapper';
28
+ const subPackageIndieCustomWrapperRootsKey = '__taroSubPackageIndieCustomWrapperRoots';
29
+ const recursiveComponentName = 'recursive-component';
28
30
  const PLUGIN_NAME = 'TaroMiniPlugin';
29
31
  const CHILD_COMPILER_TAG = 'child';
32
+ const SUBPACKAGE_STANDALONE_CHILD_TAG = 'sub_package_indie_standalone_child';
33
+ const STYLE_ISOLATION_APPLY_SHARED = 'apply-shared';
34
+ const STYLE_ISOLATION_SHARED = 'shared';
30
35
  function isLoaderExist(loaders, loaderName) {
31
36
  return loaders.some(item => item.loader === loaderName);
32
37
  }
@@ -46,6 +51,7 @@ class TaroMiniPlugin {
46
51
  this.dependencies = new Map();
47
52
  this.pageLoaderName = '@tarojs/taro-loader/lib/page';
48
53
  this.independentPackages = new Map();
54
+ this.moduleRequestMap = new Map();
49
55
  const { combination } = options;
50
56
  const miniBuildConfig = combination.config;
51
57
  const { template, baseLevel = 16, experimental } = miniBuildConfig;
@@ -135,6 +141,7 @@ class TaroMiniPlugin {
135
141
  const dependencies = this.dependencies;
136
142
  const promises = [];
137
143
  this.compileIndependentPages(compiler, compilation, dependencies, promises);
144
+ this.compileSubPackageIndieStandaloneEntries(compiler, compilation, promises);
138
145
  dependencies.forEach(dep => {
139
146
  promises.push(new Promise((resolve, reject) => {
140
147
  compilation.addEntry(this.options.sourceDir, dep, Object.assign({ name: dep.name }, dep.options), err => err ? reject(err) : resolve(null));
@@ -147,6 +154,44 @@ class TaroMiniPlugin {
147
154
  /** For Webpack compilation get factory from compilation.dependencyFactories by denpendence's constructor */
148
155
  compilation.dependencyFactories.set(EntryDependency_1.default, normalModuleFactory);
149
156
  compilation.dependencyFactories.set(TaroSingleEntryDependency_1.default, normalModuleFactory);
157
+ if (this.options.newBlended) {
158
+ normalModuleFactory.hooks.afterResolve.tap(PLUGIN_NAME, (resolveData) => {
159
+ var _a, _b;
160
+ const issuer = (_a = resolveData.contextInfo) === null || _a === void 0 ? void 0 : _a.issuer;
161
+ const request = resolveData.request;
162
+ const resource = ((_b = resolveData.createData) === null || _b === void 0 ? void 0 : _b.resource) || resolveData.resource;
163
+ if (!issuer || !request || !resource)
164
+ return;
165
+ this.setResolvedRequestResource(issuer, request, resource);
166
+ });
167
+ }
168
+ // 在 afterResolve 阶段收集每个 subPackageIndieRoot 实际使用的组件
169
+ if (this.options.newBlended) {
170
+ normalModuleFactory.hooks.afterResolve.tap(PLUGIN_NAME, (resolveData) => {
171
+ var _a;
172
+ if (resolveData.request !== helper_1.taroJsComponents)
173
+ return;
174
+ const issuer = (_a = resolveData.contextInfo) === null || _a === void 0 ? void 0 : _a.issuer;
175
+ if (!issuer || !issuer.startsWith(this.options.sourceDir))
176
+ return;
177
+ const componentName = this.getComponentName(issuer);
178
+ const root = this.isInSubPackageIndieRoot(componentName);
179
+ if (!root)
180
+ return;
181
+ resolveData.dependencies.forEach((dependency) => {
182
+ var _a;
183
+ if (((_a = dependency.ids) === null || _a === void 0 ? void 0 : _a.length) > 0) {
184
+ dependency.ids.forEach((id) => {
185
+ const dashedName = this.toDashedComponentName(id);
186
+ if (!component_1.componentConfig.scopedIncludes.has(root)) {
187
+ component_1.componentConfig.scopedIncludes.set(root, new Set());
188
+ }
189
+ component_1.componentConfig.scopedIncludes.get(root).add(dashedName);
190
+ });
191
+ }
192
+ });
193
+ });
194
+ }
150
195
  /**
151
196
  * webpack NormalModule 在 runLoaders 真正解析资源的前一刻,
152
197
  * 往 NormalModule.loaders 中插入对应的 Taro Loader
@@ -225,6 +270,8 @@ class TaroMiniPlugin {
225
270
  name: PLUGIN_NAME,
226
271
  stage: PROCESS_ASSETS_STAGE_ADDITIONAL
227
272
  }, this.tryAsync(() => __awaiter(this, void 0, void 0, function* () {
273
+ if (compilation.__tag === SUBPACKAGE_STANDALONE_CHILD_TAG)
274
+ return;
228
275
  // 如果是子编译器,证明是编译独立分包,进行单独的处理
229
276
  if (compilation.__tag === CHILD_COMPILER_TAG) {
230
277
  yield this.generateIndependentMiniFiles(compilation, compiler);
@@ -239,6 +286,8 @@ class TaroMiniPlugin {
239
286
  // Stage 触发顺序:https://webpack.js.org/api/compilation-hooks/#list-of-asset-processing-stages
240
287
  stage: PROCESS_ASSETS_STAGE_OPTIMIZE
241
288
  }, this.tryAsync(() => __awaiter(this, void 0, void 0, function* () {
289
+ if (compilation.__tag === SUBPACKAGE_STANDALONE_CHILD_TAG)
290
+ return;
242
291
  yield this.optimizeMiniFiles(compilation, compiler);
243
292
  })));
244
293
  compilation.hooks.processAssets.tapAsync({
@@ -246,6 +295,8 @@ class TaroMiniPlugin {
246
295
  // 该 stage 是最后执行的,确保 taro 暴露给用户的钩子 modifyBuildAssets 在内部处理完 assets 之后再调用
247
296
  stage: PROCESS_ASSETS_STAGE_REPORT
248
297
  }, this.tryAsync(() => __awaiter(this, void 0, void 0, function* () {
298
+ if (compilation.__tag === SUBPACKAGE_STANDALONE_CHILD_TAG)
299
+ return;
249
300
  if (typeof modifyBuildAssets === 'function') {
250
301
  yield modifyBuildAssets(compilation.assets, this);
251
302
  }
@@ -293,14 +344,27 @@ class TaroMiniPlugin {
293
344
  const entryChunk = [{ name: 'app' }];
294
345
  // 所有模块都依赖app.js,确保@tarojs\plugin-platform-xxx\dist\runtime.js先于@tarojs/runtime执行,避免Taro API未被初始化
295
346
  if (this.nativeComponents.has(id) || miniType === helper_1.META_TYPE.STATIC) {
347
+ // ★ 检查是否属于子分包独立模板
348
+ const isSubPackageIndie = this.isInSubPackageIndieRoot(id);
349
+ if (isSubPackageIndie) {
350
+ // 子分包组件不注入 require,直接返回原始模块
351
+ return modules;
352
+ }
296
353
  fileChunks.forEach((v, k) => {
297
354
  if (k === id) {
298
355
  source = (0, webpack_1.addRequireToSource)(id, modules, v);
299
356
  }
300
357
  });
301
- return source;
358
+ // 如果没有依赖需要注入,返回原始模块
359
+ return source || modules;
302
360
  }
303
361
  else if (miniType === helper_1.META_TYPE.PAGE) {
362
+ // ★ 检查是否属于子分包独立模板,使用本地 app.js
363
+ const subPackageIndieRoot = this.isInSubPackageIndieRoot(id);
364
+ if (subPackageIndieRoot) {
365
+ const localAppChunk = [{ name: `${subPackageIndieRoot}/app` }];
366
+ return (0, webpack_1.addRequireToSource)(id, modules, localAppChunk);
367
+ }
304
368
  return (0, webpack_1.addRequireToSource)(id, modules, entryChunk);
305
369
  }
306
370
  }
@@ -570,6 +634,113 @@ class TaroMiniPlugin {
570
634
  this.nativeComponents.set(item, componentObj);
571
635
  });
572
636
  }
637
+ /**
638
+ * 规范化子分包独立模板的根路径
639
+ * 如果路径以 /index 结尾(表示页面路径),则返回其父目录(文件所在目录)
640
+ * @example 'pages/index/index' => 'pages/index'
641
+ * @example 'pages/order' => 'pages/order'
642
+ */
643
+ normalizeIndieRoot(root) {
644
+ // 如果以 /index 结尾,说明是页面路径,需要取其所在目录
645
+ if (root.endsWith('/index')) {
646
+ return node_path_1.default.dirname(root);
647
+ }
648
+ return root;
649
+ }
650
+ /**
651
+ * 获取所有子分包独立模板的根路径列表(已规范化)
652
+ * @returns 规范化后的分包根路径数组,如果未配置则返回空数组
653
+ */
654
+ getAllIndieRoots() {
655
+ return Array.from(new Set(this.getSubPackageIndieConfigs().flatMap(({ mainPackageRoot, subPackageRoots }) => [mainPackageRoot, ...subPackageRoots])));
656
+ }
657
+ /**
658
+ * 获取子分包独立模板配置列表(已规范化)
659
+ */
660
+ /**
661
+ * 解析 SubPackageIndieRootConfig 联合类型,返回归一化后的路径和是否禁用递归组件
662
+ */
663
+ parseIndieRootConfig(rootConfig) {
664
+ if (typeof rootConfig === 'string') {
665
+ return { path: this.normalizeIndieRoot(rootConfig), disableRecursiveComponent: false };
666
+ }
667
+ return {
668
+ path: this.normalizeIndieRoot(rootConfig.path),
669
+ disableRecursiveComponent: !!rootConfig.disableRecursiveComponent
670
+ };
671
+ }
672
+ getSubPackageIndieConfigs() {
673
+ var _a;
674
+ const subPackageIndie = (_a = this.appConfig) === null || _a === void 0 ? void 0 : _a.subPackageIndie;
675
+ if (!Array.isArray(subPackageIndie))
676
+ return [];
677
+ return subPackageIndie.map(({ mainPackageRoot, subPackageRoots = [] }) => {
678
+ const mainParsed = this.parseIndieRootConfig(mainPackageRoot);
679
+ const subParsedList = subPackageRoots.map(root => this.parseIndieRootConfig(root));
680
+ const disableRecursiveComponentRoots = new Set();
681
+ if (mainParsed.disableRecursiveComponent) {
682
+ disableRecursiveComponentRoots.add(mainParsed.path);
683
+ }
684
+ subParsedList.forEach(sub => {
685
+ if (sub.disableRecursiveComponent) {
686
+ disableRecursiveComponentRoots.add(sub.path);
687
+ }
688
+ });
689
+ return {
690
+ mainPackageRoot: mainParsed.path,
691
+ subPackageRoots: Array.from(new Set(subParsedList.map(sub => sub.path))),
692
+ disableRecursiveComponentRoots
693
+ };
694
+ });
695
+ }
696
+ /**
697
+ * 判断给定的 indie root 是否禁用了递归组件(comp/custom-wrapper/recursive-component)
698
+ */
699
+ isRecursiveComponentDisabledForRoot(root) {
700
+ return this.getSubPackageIndieConfigs().some(config => config.disableRecursiveComponentRoots.has(root));
701
+ }
702
+ getAllMainPackageRoots() {
703
+ return Array.from(new Set(this.getSubPackageIndieConfigs().map(item => item.mainPackageRoot)));
704
+ }
705
+ getAllSubPackageRoots() {
706
+ return Array.from(new Set(this.getSubPackageIndieConfigs().flatMap(item => item.subPackageRoots)));
707
+ }
708
+ hasSubPackageIndieMainPackageRoot() {
709
+ return this.getAllMainPackageRoots().length > 0;
710
+ }
711
+ getSubPackageIndieMatch(pageName) {
712
+ const { newBlended } = this.options;
713
+ if (!newBlended)
714
+ return null;
715
+ const configs = this.getSubPackageIndieConfigs();
716
+ for (const config of configs) {
717
+ if (pageName.startsWith(config.mainPackageRoot + '/') || pageName === config.mainPackageRoot) {
718
+ return {
719
+ config,
720
+ root: config.mainPackageRoot,
721
+ isMainPackageRoot: true
722
+ };
723
+ }
724
+ for (const root of config.subPackageRoots) {
725
+ if (pageName.startsWith(root + '/') || pageName === root) {
726
+ return {
727
+ config,
728
+ root,
729
+ isMainPackageRoot: false
730
+ };
731
+ }
732
+ }
733
+ }
734
+ return null;
735
+ }
736
+ /**
737
+ * 判断给定路径是否属于子分包独立模板的分包(包括 mainPackageRoot 和 subPackageRoots)
738
+ * @returns 匹配的分包根路径(已规范化),或 null
739
+ */
740
+ isInSubPackageIndieRoot(pageName) {
741
+ var _a;
742
+ return ((_a = this.getSubPackageIndieMatch(pageName)) === null || _a === void 0 ? void 0 : _a.root) || null;
743
+ }
573
744
  /**
574
745
  * 读取页面及其依赖的组件的配置
575
746
  */
@@ -611,8 +782,11 @@ class TaroMiniPlugin {
611
782
  */
612
783
  addEntry(entryPath, entryName, entryType, options = {}) {
613
784
  let dep;
614
- if (this.dependencies.has(entryPath)) {
615
- dep = this.dependencies.get(entryPath);
785
+ // 对于 STATIC 类型(如 comp/custom-wrapper),使用 entryName 作为 key 的一部分
786
+ // 这允许同一个模板文件被多次添加为不同名称的入口
787
+ const depKey = entryType === helper_1.META_TYPE.STATIC ? `${entryPath}#${entryName}` : entryPath;
788
+ if (this.dependencies.has(depKey)) {
789
+ dep = this.dependencies.get(depKey);
616
790
  dep.name = entryName;
617
791
  dep.loc = { name: entryName };
618
792
  dep.request = entryPath;
@@ -623,18 +797,23 @@ class TaroMiniPlugin {
623
797
  else {
624
798
  dep = new TaroSingleEntryDependency_1.default(entryPath, entryName, { name: entryName }, entryType, options);
625
799
  }
626
- this.dependencies.set(entryPath, dep);
800
+ this.dependencies.set(depKey, dep);
627
801
  }
628
802
  /**
629
803
  * 在 this.dependencies 中新增或修改 app、模板组件、页面、组件等资源模块
630
804
  */
631
805
  addEntries() {
632
- const { template } = this.options;
806
+ const { template, newBlended } = this.options;
633
807
  this.addEntry(this.appEntry, 'app', helper_1.META_TYPE.ENTRY);
634
- if (!template.isSupportRecursive) {
808
+ // 当配置了 mainPackageRoot 时,跳过根目录 comp 和 custom-wrapper 入口
809
+ const skipRootEntries = this.hasSubPackageIndieMainPackageRoot() && newBlended;
810
+ if (!template.isSupportRecursive && !skipRootEntries) {
635
811
  this.addEntry(node_path_1.default.resolve(__dirname, '..', 'template/comp'), 'comp', helper_1.META_TYPE.STATIC);
636
812
  }
637
- this.addEntry(node_path_1.default.resolve(__dirname, '..', 'template/custom-wrapper'), 'custom-wrapper', helper_1.META_TYPE.STATIC);
813
+ if (!skipRootEntries) {
814
+ this.addEntry(node_path_1.default.resolve(__dirname, '..', 'template/custom-wrapper'), 'custom-wrapper', helper_1.META_TYPE.STATIC);
815
+ }
816
+ // subPackageIndie 下的 comp/custom-wrapper 统一走独立子编译器,避免被主编译的公共 chunk 共享
638
817
  this.pages.forEach(item => {
639
818
  if (item.isNative) {
640
819
  this.addEntry(item.path, item.name, helper_1.META_TYPE.NORMAL, { isNativePage: true });
@@ -900,6 +1079,45 @@ class TaroMiniPlugin {
900
1079
  });
901
1080
  }
902
1081
  }
1082
+ compileSubPackageIndieStandaloneEntries(compiler, compilation, promises) {
1083
+ const { newBlended } = this.options;
1084
+ const indieRoots = this.getAllIndieRoots();
1085
+ if (!newBlended || !indieRoots.length)
1086
+ return;
1087
+ const JsonpTemplatePlugin = require('webpack/lib/web/JsonpTemplatePlugin');
1088
+ const NaturalChunkIdsPlugin = require('webpack/lib/ids/NaturalChunkIdsPlugin');
1089
+ indieRoots.forEach(root => {
1090
+ // ★ 禁用递归组件的 root 不需要编译 recursive-component
1091
+ if (this.isRecursiveComponentDisabledForRoot(root))
1092
+ return;
1093
+ const childCompiler = compilation.createChildCompiler(PLUGIN_NAME, {
1094
+ path: compiler.options.output.path,
1095
+ filename: '[name].js',
1096
+ chunkFilename: '[name].js',
1097
+ chunkLoadingGlobal: `subpackage_indie_${root.replace(/[\\/]/g, '_')}`
1098
+ });
1099
+ childCompiler.inputFileSystem = compiler.inputFileSystem;
1100
+ childCompiler.outputFileSystem = compiler.outputFileSystem;
1101
+ childCompiler.context = compiler.context;
1102
+ new JsonpTemplatePlugin().apply(childCompiler);
1103
+ new NaturalChunkIdsPlugin().apply(childCompiler);
1104
+ new compiler.webpack.DefinePlugin(this.options.constantsReplaceList).apply(childCompiler);
1105
+ childCompiler.hooks.compilation.tap(PLUGIN_NAME, (childCompilation) => {
1106
+ childCompilation.__tag = SUBPACKAGE_STANDALONE_CHILD_TAG;
1107
+ childCompilation.__name = root;
1108
+ });
1109
+ childCompiler.options.optimization = Object.assign(Object.assign({}, childCompiler.options.optimization), { splitChunks: false, runtimeChunk: false });
1110
+ const outputOptions = childCompiler.options.output || {};
1111
+ const libraryOptions = typeof outputOptions.library === 'object' && outputOptions.library !== null
1112
+ ? outputOptions.library
1113
+ : {};
1114
+ childCompiler.options.output = Object.assign(Object.assign({}, outputOptions), { library: Object.assign(Object.assign({}, libraryOptions), { type: 'commonjs2' }) });
1115
+ new TaroSingleEntryPlugin_1.default(compiler.context, node_path_1.default.resolve(__dirname, '..', 'template/recursive-component'), `${root}/${recursiveComponentName}`, helper_1.META_TYPE.EXPORTS).apply(childCompiler);
1116
+ promises.push(new Promise((resolve, reject) => {
1117
+ childCompiler.runAsChild(err => err ? reject(err) : resolve(null));
1118
+ }));
1119
+ });
1120
+ }
903
1121
  /**
904
1122
  * 搜集 tabbar icon 图标路径
905
1123
  * 收集自定义 tabbar 组件
@@ -962,6 +1180,552 @@ class TaroMiniPlugin {
962
1180
  usingComponents[key] = match ? `${node_path_1.default.sep}${match[0]}` : compPath;
963
1181
  }
964
1182
  }
1183
+ cloneThirdPartyComponent(thirdPartyComponents, componentName) {
1184
+ const attrs = component_1.componentConfig.thirdPartyComponents.get(componentName);
1185
+ if (!attrs || thirdPartyComponents.has(componentName))
1186
+ return;
1187
+ thirdPartyComponents.set(componentName, new Set(attrs));
1188
+ }
1189
+ getSubPackageIndieEntriesByRoot(root) {
1190
+ const entries = new Map();
1191
+ [...this.pages, ...this.components].forEach(item => {
1192
+ if (this.isInSubPackageIndieRoot(item.name) === root) {
1193
+ entries.set(item.name, item);
1194
+ }
1195
+ });
1196
+ return Array.from(entries.values());
1197
+ }
1198
+ getSubPackageIndieEntryNamesByRoot(root) {
1199
+ return this.getSubPackageIndieEntriesByRoot(root).map(item => item.name);
1200
+ }
1201
+ getComponentByName(componentName) {
1202
+ return [...this.pages, ...this.components].find(item => item.name === componentName);
1203
+ }
1204
+ getChunksBySubPackageIndieRoot(compilation, root) {
1205
+ const chunks = new Set();
1206
+ this.getSubPackageIndieEntryNamesByRoot(root).forEach(entryName => {
1207
+ const entryChunk = Array.from(compilation.chunks).find(chunk => chunk.name === entryName);
1208
+ if (!entryChunk)
1209
+ return;
1210
+ chunks.add(entryChunk);
1211
+ entryChunk.groupsIterable.forEach(group => {
1212
+ group.chunks.forEach(chunk => chunks.add(chunk));
1213
+ });
1214
+ });
1215
+ return chunks;
1216
+ }
1217
+ getModuleSourceContent(module) {
1218
+ var _a;
1219
+ try {
1220
+ const source = (_a = module === null || module === void 0 ? void 0 : module.originalSource) === null || _a === void 0 ? void 0 : _a.call(module);
1221
+ if (!source || typeof source.source !== 'function')
1222
+ return '';
1223
+ return String(source.source() || '');
1224
+ }
1225
+ catch (_err) {
1226
+ return '';
1227
+ }
1228
+ }
1229
+ getModuleResource(module) {
1230
+ var _a;
1231
+ const resource = (module === null || module === void 0 ? void 0 : module.resource) || ((_a = module === null || module === void 0 ? void 0 : module.rootModule) === null || _a === void 0 ? void 0 : _a.resource);
1232
+ return typeof resource === 'string' ? resource : undefined;
1233
+ }
1234
+ collectFlattenedModules(module, collected, visited = new Set()) {
1235
+ if (!module || visited.has(module))
1236
+ return;
1237
+ visited.add(module);
1238
+ collected.add(module);
1239
+ const nestedModuleCollections = [module.rootModule, module.modules, module._modules];
1240
+ nestedModuleCollections.forEach(item => {
1241
+ if (!item)
1242
+ return;
1243
+ if (item && typeof item[Symbol.iterator] === 'function') {
1244
+ for (const nested of item) {
1245
+ this.collectFlattenedModules(nested, collected, visited);
1246
+ }
1247
+ }
1248
+ else {
1249
+ this.collectFlattenedModules(item, collected, visited);
1250
+ }
1251
+ });
1252
+ }
1253
+ getCompilationModuleResourceMap(compilation) {
1254
+ const moduleMap = new Map();
1255
+ for (const module of compilation.modules) {
1256
+ const flattenedModules = new Set();
1257
+ this.collectFlattenedModules(module, flattenedModules);
1258
+ flattenedModules.forEach(flattenedModule => {
1259
+ const resource = this.getModuleResource(flattenedModule);
1260
+ if (resource) {
1261
+ moduleMap.set(resource, flattenedModule);
1262
+ }
1263
+ });
1264
+ }
1265
+ return moduleMap;
1266
+ }
1267
+ getSubPackageIndieModules(compilation, root) {
1268
+ const modules = new Set();
1269
+ this.getChunksBySubPackageIndieRoot(compilation, root).forEach(chunk => {
1270
+ for (const module of compilation.chunkGraph.getChunkModulesIterable(chunk)) {
1271
+ this.collectFlattenedModules(module, modules);
1272
+ }
1273
+ });
1274
+ return modules;
1275
+ }
1276
+ normalizeModuleRequestMapKey(resource) {
1277
+ if (!resource || typeof resource !== 'string')
1278
+ return null;
1279
+ const resourceWithoutLoader = resource.split('!').pop();
1280
+ if (!resourceWithoutLoader)
1281
+ return null;
1282
+ const resourcePath = resourceWithoutLoader.split('?')[0];
1283
+ if (!resourcePath)
1284
+ return null;
1285
+ return node_path_1.default.normalize(resourcePath);
1286
+ }
1287
+ getModuleRequestMapKeys(resource) {
1288
+ const keys = new Set();
1289
+ if (resource && typeof resource === 'string') {
1290
+ keys.add(resource);
1291
+ }
1292
+ const normalizedResource = this.normalizeModuleRequestMapKey(resource);
1293
+ if (normalizedResource) {
1294
+ keys.add(normalizedResource);
1295
+ }
1296
+ return Array.from(keys);
1297
+ }
1298
+ setResolvedRequestResource(issuer, request, resource) {
1299
+ this.getModuleRequestMapKeys(issuer).forEach(key => {
1300
+ if (!this.moduleRequestMap.has(key)) {
1301
+ this.moduleRequestMap.set(key, new Map());
1302
+ }
1303
+ this.moduleRequestMap.get(key).set(request, resource);
1304
+ });
1305
+ }
1306
+ getResolvedRequestResource(issuerResource, request) {
1307
+ var _a;
1308
+ for (const key of this.getModuleRequestMapKeys(issuerResource)) {
1309
+ const resolvedResource = (_a = this.moduleRequestMap.get(key)) === null || _a === void 0 ? void 0 : _a.get(request);
1310
+ if (resolvedResource)
1311
+ return resolvedResource;
1312
+ }
1313
+ }
1314
+ getResolvedModuleByResource(moduleResourceMap, resource) {
1315
+ const exactModule = moduleResourceMap.get(resource);
1316
+ if (exactModule)
1317
+ return exactModule;
1318
+ const normalizedResource = this.normalizeModuleRequestMapKey(resource);
1319
+ if (!normalizedResource)
1320
+ return null;
1321
+ const normalizedModule = moduleResourceMap.get(normalizedResource);
1322
+ if (normalizedModule)
1323
+ return normalizedModule;
1324
+ for (const [moduleResource, module] of moduleResourceMap.entries()) {
1325
+ if (this.normalizeModuleRequestMapKey(moduleResource) === normalizedResource) {
1326
+ return module;
1327
+ }
1328
+ }
1329
+ return null;
1330
+ }
1331
+ resolveRequestedModule(moduleResourceMap, issuerModule, request) {
1332
+ const issuerResource = this.getModuleResource(issuerModule);
1333
+ const resolvedResource = this.getResolvedRequestResource(issuerResource, request);
1334
+ if (resolvedResource) {
1335
+ const resolvedModule = this.getResolvedModuleByResource(moduleResourceMap, resolvedResource);
1336
+ if (resolvedModule)
1337
+ return resolvedModule;
1338
+ }
1339
+ if (issuerResource && /^[.\\/]/.test(request)) {
1340
+ const requestPath = node_path_1.default.resolve(node_path_1.default.dirname(issuerResource), request);
1341
+ const resolvedPath = (0, helper_1.resolveMainFilePath)(requestPath);
1342
+ const requestModule = this.getResolvedModuleByResource(moduleResourceMap, resolvedPath);
1343
+ if (requestModule)
1344
+ return requestModule;
1345
+ }
1346
+ for (const module of moduleResourceMap.values()) {
1347
+ if (!module)
1348
+ continue;
1349
+ if (module.rawRequest === request || module.userRequest === request || module.request === request) {
1350
+ return module;
1351
+ }
1352
+ }
1353
+ return null;
1354
+ }
1355
+ resolveImportBindingToTaroComponentName(moduleResourceMap, issuerModule, binding, propertyName, visited = new Set()) {
1356
+ if (!(binding === null || binding === void 0 ? void 0 : binding.source))
1357
+ return null;
1358
+ if (binding.kind === 'namespace') {
1359
+ if (!propertyName)
1360
+ return null;
1361
+ if (binding.source === helper_1.taroJsComponents) {
1362
+ return propertyName;
1363
+ }
1364
+ const targetModule = this.resolveRequestedModule(moduleResourceMap, issuerModule, binding.source);
1365
+ if (!targetModule) {
1366
+ if (!/^[.\\/]/.test(binding.source)) {
1367
+ return propertyName;
1368
+ }
1369
+ return null;
1370
+ }
1371
+ return this.resolveModuleExportToTaroComponentName(moduleResourceMap, targetModule, propertyName, visited);
1372
+ }
1373
+ const importedName = binding.imported || propertyName;
1374
+ if (!importedName || importedName === 'default')
1375
+ return null;
1376
+ if (binding.source === helper_1.taroJsComponents) {
1377
+ return importedName;
1378
+ }
1379
+ const targetModule = this.resolveRequestedModule(moduleResourceMap, issuerModule, binding.source);
1380
+ if (!targetModule) {
1381
+ if (!/^[.\\/]/.test(binding.source)) {
1382
+ return importedName;
1383
+ }
1384
+ return null;
1385
+ }
1386
+ return this.resolveModuleExportToTaroComponentName(moduleResourceMap, targetModule, importedName, visited);
1387
+ }
1388
+ resolveModuleExportToTaroComponentName(moduleResourceMap, module, exportName, visited = new Set()) {
1389
+ var _a, _b;
1390
+ const moduleResource = this.getModuleResource(module);
1391
+ if (!moduleResource)
1392
+ return null;
1393
+ const visitKey = `${moduleResource}::${exportName}`;
1394
+ if (visited.has(visitKey))
1395
+ return null;
1396
+ visited.add(visitKey);
1397
+ const exportBinding = (_a = module === null || module === void 0 ? void 0 : module.exportBindings) === null || _a === void 0 ? void 0 : _a[exportName];
1398
+ if (exportBinding) {
1399
+ if (exportBinding.kind === 'reexport' && exportBinding.source) {
1400
+ if (exportBinding.source === helper_1.taroJsComponents) {
1401
+ return exportBinding.imported || exportName;
1402
+ }
1403
+ const targetModule = this.resolveRequestedModule(moduleResourceMap, module, exportBinding.source);
1404
+ if (targetModule) {
1405
+ const resolvedName = this.resolveModuleExportToTaroComponentName(moduleResourceMap, targetModule, exportBinding.imported || exportName, visited);
1406
+ if (resolvedName)
1407
+ return resolvedName;
1408
+ }
1409
+ }
1410
+ if (exportBinding.kind === 'local' && exportBinding.local) {
1411
+ const importedBinding = (_b = module === null || module === void 0 ? void 0 : module.importedBindings) === null || _b === void 0 ? void 0 : _b[exportBinding.local];
1412
+ if (importedBinding) {
1413
+ const resolvedName = this.resolveImportBindingToTaroComponentName(moduleResourceMap, module, importedBinding, undefined, visited);
1414
+ if (resolvedName)
1415
+ return resolvedName;
1416
+ }
1417
+ }
1418
+ }
1419
+ for (const source of (module === null || module === void 0 ? void 0 : module.exportAllSources) || []) {
1420
+ if (source === helper_1.taroJsComponents) {
1421
+ return exportName;
1422
+ }
1423
+ const targetModule = this.resolveRequestedModule(moduleResourceMap, module, source);
1424
+ if (!targetModule)
1425
+ continue;
1426
+ const resolvedName = this.resolveModuleExportToTaroComponentName(moduleResourceMap, targetModule, exportName, visited);
1427
+ if (resolvedName)
1428
+ return resolvedName;
1429
+ }
1430
+ return null;
1431
+ }
1432
+ resolveUsedComponentRefToTaroComponentName(moduleResourceMap, module, componentRef) {
1433
+ var _a, _b;
1434
+ if (!componentRef)
1435
+ return null;
1436
+ if (componentRef.kind === 'identifier') {
1437
+ const binding = (_a = module === null || module === void 0 ? void 0 : module.importedBindings) === null || _a === void 0 ? void 0 : _a[componentRef.name];
1438
+ if (!binding) {
1439
+ return componentRef.name;
1440
+ }
1441
+ const resolvedName = this.resolveImportBindingToTaroComponentName(moduleResourceMap, module, binding);
1442
+ return resolvedName || componentRef.name;
1443
+ }
1444
+ if (componentRef.kind === 'member') {
1445
+ const binding = (_b = module === null || module === void 0 ? void 0 : module.importedBindings) === null || _b === void 0 ? void 0 : _b[componentRef.object];
1446
+ if (!binding) {
1447
+ return componentRef.property || null;
1448
+ }
1449
+ const resolvedName = this.resolveImportBindingToTaroComponentName(moduleResourceMap, module, binding, componentRef.property);
1450
+ return resolvedName || componentRef.property || null;
1451
+ }
1452
+ return null;
1453
+ }
1454
+ isSubPackageIndieRootUsingCustomWrapperByModules(compilation, root) {
1455
+ const moduleResourceMap = this.getCompilationModuleResourceMap(compilation);
1456
+ for (const module of this.getSubPackageIndieModules(compilation, root)) {
1457
+ if (this.shouldSkipSubPackageIndieModule(module, root))
1458
+ continue;
1459
+ for (const componentRef of (module === null || module === void 0 ? void 0 : module.usedComponentRefs) || []) {
1460
+ const resolvedComponentName = this.resolveUsedComponentRefToTaroComponentName(moduleResourceMap, module, componentRef);
1461
+ if (resolvedComponentName === 'CustomWrapper') {
1462
+ return true;
1463
+ }
1464
+ }
1465
+ }
1466
+ return false;
1467
+ }
1468
+ shouldSkipSubPackageIndieModule(module, root) {
1469
+ const resource = this.getModuleResource(module);
1470
+ if (typeof resource !== 'string' || !resource.startsWith(this.options.sourceDir)) {
1471
+ return false;
1472
+ }
1473
+ const componentName = this.getComponentName(resource);
1474
+ const targetRoot = this.isInSubPackageIndieRoot(componentName);
1475
+ return !!targetRoot && targetRoot !== root;
1476
+ }
1477
+ collectModuleResolvedComponentIncludes(compilation, root) {
1478
+ const includes = new Set();
1479
+ const moduleResourceMap = this.getCompilationModuleResourceMap(compilation);
1480
+ for (const module of this.getSubPackageIndieModules(compilation, root)) {
1481
+ if (this.shouldSkipSubPackageIndieModule(module, root))
1482
+ continue;
1483
+ for (const elementName of (module === null || module === void 0 ? void 0 : module.elementNameSet) || []) {
1484
+ if (!component_1.componentConfig.thirdPartyComponents.has(elementName)) {
1485
+ includes.add(elementName);
1486
+ }
1487
+ }
1488
+ for (const binding of Object.values((module === null || module === void 0 ? void 0 : module.importedBindings) || {})) {
1489
+ const resolvedComponentName = this.resolveImportBindingToTaroComponentName(moduleResourceMap, module, binding);
1490
+ if (!resolvedComponentName)
1491
+ continue;
1492
+ const dashedName = this.toDashedComponentName(resolvedComponentName);
1493
+ if (!component_1.componentConfig.thirdPartyComponents.has(dashedName)) {
1494
+ includes.add(dashedName);
1495
+ }
1496
+ }
1497
+ for (const componentRef of (module === null || module === void 0 ? void 0 : module.usedComponentRefs) || []) {
1498
+ const resolvedComponentName = this.resolveUsedComponentRefToTaroComponentName(moduleResourceMap, module, componentRef);
1499
+ if (!resolvedComponentName)
1500
+ continue;
1501
+ const dashedName = this.toDashedComponentName(resolvedComponentName);
1502
+ if (!component_1.componentConfig.thirdPartyComponents.has(dashedName)) {
1503
+ includes.add(dashedName);
1504
+ }
1505
+ }
1506
+ }
1507
+ return includes;
1508
+ }
1509
+ expandScopedIncludes(includes) {
1510
+ const scopedIncludes = new Set(includes);
1511
+ if (scopedIncludes.has('view')) {
1512
+ scopedIncludes.add('catch-view');
1513
+ scopedIncludes.add('static-view');
1514
+ scopedIncludes.add('pure-view');
1515
+ scopedIncludes.add('click-view');
1516
+ }
1517
+ if (scopedIncludes.has('image')) {
1518
+ scopedIncludes.add('static-image');
1519
+ }
1520
+ if (scopedIncludes.has('text')) {
1521
+ scopedIncludes.add('static-text');
1522
+ }
1523
+ return scopedIncludes;
1524
+ }
1525
+ toDashedComponentName(componentName) {
1526
+ return componentName.replace(/[A-Z]/g, (match, offset) => `${offset === 0 ? '' : '-'}${match.toLowerCase()}`);
1527
+ }
1528
+ collectScopedInnerComponents(compilation, root) {
1529
+ const includes = new Set();
1530
+ const scopedIncludes = component_1.componentConfig.scopedIncludes.get(root);
1531
+ if (scopedIncludes && scopedIncludes.size > 0) {
1532
+ scopedIncludes.forEach(name => includes.add(name));
1533
+ }
1534
+ this.collectModuleResolvedComponentIncludes(compilation, root).forEach(name => includes.add(name));
1535
+ const finalIncludes = includes.size > 0
1536
+ ? includes
1537
+ : new Set(component_1.componentConfig.includes);
1538
+ return this.expandScopedIncludes(finalIncludes);
1539
+ }
1540
+ isSubPackageIndieRootUsingCustomWrapper(compilation, root, scopedThirdPartyComponents) {
1541
+ if (scopedThirdPartyComponents === null || scopedThirdPartyComponents === void 0 ? void 0 : scopedThirdPartyComponents.has(customWrapperName)) {
1542
+ return true;
1543
+ }
1544
+ if (this.isSubPackageIndieRootUsingCustomWrapperByModules(compilation, root)) {
1545
+ return true;
1546
+ }
1547
+ return false;
1548
+ }
1549
+ resolveUsingComponentTarget(filePath, componentPath) {
1550
+ if (componentPath.startsWith('plugin://'))
1551
+ return null;
1552
+ let sourcePath = componentPath;
1553
+ if (node_path_1.default.isAbsolute(componentPath)) {
1554
+ sourcePath = helper_1.fs.existsSync(componentPath)
1555
+ ? componentPath
1556
+ : node_path_1.default.resolve(this.options.sourceDir, `.${componentPath}`);
1557
+ }
1558
+ else {
1559
+ const isRelativePath = /^[.\\/]/;
1560
+ if (!isRelativePath.test(componentPath))
1561
+ return null;
1562
+ sourcePath = node_path_1.default.resolve(node_path_1.default.dirname(filePath), componentPath);
1563
+ }
1564
+ const targetPath = (0, helper_1.resolveMainFilePath)(sourcePath);
1565
+ const targetName = this.getComponentName(targetPath);
1566
+ return {
1567
+ path: targetPath,
1568
+ name: targetName,
1569
+ root: this.isInSubPackageIndieRoot(targetName)
1570
+ };
1571
+ }
1572
+ getScopedSubPackageIndieComponentConfig(compilation, root) {
1573
+ var _a;
1574
+ const thirdPartyComponents = new Map();
1575
+ const queue = this.getSubPackageIndieEntriesByRoot(root);
1576
+ const visited = new Set();
1577
+ while (queue.length) {
1578
+ const current = queue.shift();
1579
+ if (!current || visited.has(current.name))
1580
+ continue;
1581
+ visited.add(current.name);
1582
+ const fileConfig = (_a = this.filesConfig[this.getConfigFilePath(current.name)]) === null || _a === void 0 ? void 0 : _a.content;
1583
+ const usingComponents = fileConfig === null || fileConfig === void 0 ? void 0 : fileConfig.usingComponents;
1584
+ if (!usingComponents)
1585
+ continue;
1586
+ for (const [componentName, componentValue] of Object.entries(usingComponents)) {
1587
+ if (componentName === customWrapperName) {
1588
+ this.cloneThirdPartyComponent(thirdPartyComponents, componentName);
1589
+ continue;
1590
+ }
1591
+ if (!component_1.componentConfig.thirdPartyComponents.has(componentName))
1592
+ continue;
1593
+ const componentPath = componentValue instanceof Array ? componentValue[0] : componentValue;
1594
+ const target = this.resolveUsingComponentTarget(current.path, componentPath);
1595
+ this.cloneThirdPartyComponent(thirdPartyComponents, componentName);
1596
+ if (!target)
1597
+ continue;
1598
+ const targetComponent = this.getComponentByName(target.name);
1599
+ if (targetComponent && (!target.root || target.root === root) && !visited.has(targetComponent.name)) {
1600
+ queue.push(targetComponent);
1601
+ }
1602
+ }
1603
+ }
1604
+ return {
1605
+ includes: this.collectScopedInnerComponents(compilation, root),
1606
+ exclude: new Set(component_1.componentConfig.exclude),
1607
+ thirdPartyComponents,
1608
+ includeAll: false,
1609
+ skipRecursiveComponent: false
1610
+ };
1611
+ }
1612
+ /**
1613
+ * 为子分包独立模板生成相关文件
1614
+ * - base.wxml: 完整模板
1615
+ * - utils.wxs: WXS 辅助脚本
1616
+ * - comp.wxml: 组件模板(引用本地 base.wxml)
1617
+ * - comp.json: 组件配置
1618
+ * - custom-wrapper.wxml/json: (如果需要)
1619
+ */
1620
+ generateSubPackageIndieFiles(compilation, compiler, template, baseTemplateName) {
1621
+ const customWrapperRoots = new Set();
1622
+ if (!this.getSubPackageIndieConfigs().length)
1623
+ return customWrapperRoots;
1624
+ const allIndieRoots = this.getAllIndieRoots();
1625
+ allIndieRoots.forEach(root => {
1626
+ const scopedComponentConfig = this.getScopedSubPackageIndieComponentConfig(compilation, root);
1627
+ // ★ 检查该 root 是否禁用了递归组件
1628
+ const isRecursiveDisabled = this.isRecursiveComponentDisabledForRoot(root);
1629
+ if (isRecursiveDisabled) {
1630
+ scopedComponentConfig.skipRecursiveComponent = true;
1631
+ }
1632
+ const isRootUsingCustomWrapper = isRecursiveDisabled
1633
+ ? false
1634
+ : this.isSubPackageIndieRootUsingCustomWrapper(compilation, root, scopedComponentConfig.thirdPartyComponents);
1635
+ if (isRootUsingCustomWrapper) {
1636
+ customWrapperRoots.add(root);
1637
+ // base.wxml 模板生成依赖 thirdPartyComponents,确保 custom-wrapper 模板不会漏掉
1638
+ if (!scopedComponentConfig.thirdPartyComponents.has(customWrapperName)) {
1639
+ const attrs = component_1.componentConfig.thirdPartyComponents.get(customWrapperName);
1640
+ scopedComponentConfig.thirdPartyComponents.set(customWrapperName, new Set(attrs || []));
1641
+ }
1642
+ }
1643
+ // 1. 生成 base.wxml
1644
+ this.generateTemplateFile(compilation, compiler, `${root}/${baseTemplateName}`, template.buildTemplate, scopedComponentConfig);
1645
+ // 2. 生成 utils.wxs
1646
+ this.generateXSFile(compilation, compiler, `${root}/utils`);
1647
+ // 3. 生成 comp.wxml 和 comp.json(如果不支持递归模板且未禁用递归组件)
1648
+ if (!template.isSupportRecursive && !isRecursiveDisabled) {
1649
+ this.generateSubPackageIndieScriptFile(compilation, compiler, `${root}/${baseCompName}`, this.createRecursiveComponentWrapperSource());
1650
+ this.generateTemplateFile(compilation, compiler, `${root}/${baseCompName}`, template.buildBaseComponentTemplate, this.options.fileType.templ);
1651
+ const compConfig = {
1652
+ component: true,
1653
+ styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1654
+ usingComponents: {
1655
+ [baseCompName]: `./${baseCompName}`
1656
+ }
1657
+ };
1658
+ // 只有使用 custom-wrapper 时才添加引用
1659
+ if (isRootUsingCustomWrapper) {
1660
+ compConfig.usingComponents[customWrapperName] = `./${customWrapperName}`;
1661
+ }
1662
+ this.generateConfigFile(compilation, compiler, `${root}/${baseCompName}`, compConfig);
1663
+ }
1664
+ // 4. 生成 custom-wrapper(如果需要)
1665
+ if (isRootUsingCustomWrapper) {
1666
+ this.generateSubPackageIndieScriptFile(compilation, compiler, `${root}/${customWrapperName}`, this.createRecursiveComponentWrapperSource(customWrapperName));
1667
+ this.generateTemplateFile(compilation, compiler, `${root}/${customWrapperName}`, template.buildCustomComponentTemplate, this.options.fileType.templ);
1668
+ this.generateConfigFile(compilation, compiler, `${root}/${customWrapperName}`, {
1669
+ component: true,
1670
+ styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1671
+ usingComponents: {
1672
+ [baseCompName]: `./${baseCompName}`,
1673
+ [customWrapperName]: `./${customWrapperName}`
1674
+ }
1675
+ });
1676
+ }
1677
+ });
1678
+ return customWrapperRoots;
1679
+ }
1680
+ /**
1681
+ * 为所有 mainPackageRoot 生成 runtime chunks 文件
1682
+ * 将 app.js, runtime.js, taro.js, vendors.js, common.js 等文件复制到各 mainPackageRoot 目录
1683
+ */
1684
+ generateMainPackageRuntimeFiles(compilation, _compiler) {
1685
+ const { commonChunks, fileType } = this.options;
1686
+ const mainPackageRoots = this.getAllMainPackageRoots();
1687
+ if (!mainPackageRoots.length)
1688
+ return;
1689
+ const styleExt = fileType.style;
1690
+ // runtime chunks 列表
1691
+ const runtimeChunks = ['app', ...commonChunks];
1692
+ mainPackageRoots.forEach(mainPackageRoot => {
1693
+ runtimeChunks.forEach(chunkName => {
1694
+ var _a, _b, _c;
1695
+ // 复制 JS 文件
1696
+ const jsFile = `${chunkName}.js`;
1697
+ if (compilation.assets[jsFile]) {
1698
+ let jsContent = compilation.assets[jsFile];
1699
+ // 对 app.js 注入递归组件全局初始化代码(subpackageindie 模式)
1700
+ // 这里必须注入到 webpack 模块上下文中,避免在文件顶层使用小程序原生 require('@tarojs/runtime') 导致运行时异常
1701
+ if (chunkName === 'app') {
1702
+ const { RawSource } = ((_b = (_a = compilation.compiler) === null || _a === void 0 ? void 0 : _a.webpack) === null || _b === void 0 ? void 0 : _b.sources) || require('webpack').sources;
1703
+ const originalSource = String(((_c = jsContent.source) === null || _c === void 0 ? void 0 : _c.call(jsContent)) || jsContent.toString());
1704
+ const registrarExpr = `(typeof globalThis.__taroRegisterRecursiveComponent==="function"||(globalThis.__taroRegisterRecursiveComponent=function(componentName){const cache=__webpack_require__.c||{};let createRecursiveComponentConfig;for(const key in cache){const exports=cache[key]&&cache[key].exports;if(exports&&typeof exports.createRecursiveComponentConfig==="function"){createRecursiveComponentConfig=exports.createRecursiveComponentConfig;break;}}if(typeof createRecursiveComponentConfig!=="function"){const modules=__webpack_require__.m||{};for(const moduleId in modules){const moduleFactory=modules[moduleId];if(!moduleFactory||typeof moduleFactory!=="function")continue;const source=String(moduleFactory);if(source.indexOf("createRecursiveComponentConfig")===-1)continue;const exports=__webpack_require__(moduleId);if(exports&&typeof exports.createRecursiveComponentConfig==="function"){createRecursiveComponentConfig=exports.createRecursiveComponentConfig;break;}}}if(typeof createRecursiveComponentConfig!=="function"){throw new Error("Cannot find createRecursiveComponentConfig in webpack modules");}Component(createRecursiveComponentConfig(componentName));}))`;
1705
+ let patchedSource = originalSource;
1706
+ if (/,\s*exports\.taroApp\s*=/.test(patchedSource)) {
1707
+ patchedSource = patchedSource.replace(/,\s*exports\.taroApp\s*=/, `,${registrarExpr},exports.taroApp=`);
1708
+ }
1709
+ else {
1710
+ patchedSource = patchedSource.replace(/exports\.taroApp\s*=/, `;${registrarExpr};exports.taroApp=`);
1711
+ }
1712
+ jsContent = new RawSource(patchedSource);
1713
+ }
1714
+ compilation.assets[`${mainPackageRoot}/${jsFile}`] = jsContent;
1715
+ }
1716
+ // 复制 wxss 文件
1717
+ const cssFile = `${chunkName}${styleExt}`;
1718
+ if (compilation.assets[cssFile]) {
1719
+ compilation.assets[`${mainPackageRoot}/${cssFile}`] = compilation.assets[cssFile];
1720
+ }
1721
+ });
1722
+ // 复制 app-origin.wxss(原始样式文件)
1723
+ const appOriginCss = `app-origin${styleExt}`;
1724
+ if (compilation.assets[appOriginCss]) {
1725
+ compilation.assets[`${mainPackageRoot}/${appOriginCss}`] = compilation.assets[appOriginCss];
1726
+ }
1727
+ });
1728
+ }
965
1729
  /** 生成小程序独立分包的相关文件 */
966
1730
  generateIndependentMiniFiles(compilation, compiler) {
967
1731
  return __awaiter(this, void 0, void 0, function* () {
@@ -978,19 +1742,22 @@ class TaroMiniPlugin {
978
1742
  this.generateTemplateFile(compilation, compiler, `${name}/${baseTemplateName}`, template.buildTemplate, component_1.componentConfig);
979
1743
  if (!template.isSupportRecursive) {
980
1744
  // 如微信、QQ 不支持递归模版的小程序,需要使用自定义组件协助递归
981
- this.generateConfigFile(compilation, compiler, `${name}/${baseCompName}`, {
1745
+ const compConfig = {
982
1746
  component: true,
983
- styleIsolation: 'apply-shared',
1747
+ styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
984
1748
  usingComponents: {
985
- [baseCompName]: `./${baseCompName}`,
986
- [customWrapperName]: `./${customWrapperName}`
1749
+ [baseCompName]: `./${baseCompName}`
987
1750
  }
988
- });
1751
+ };
1752
+ if (isUsingCustomWrapper) {
1753
+ compConfig.usingComponents[customWrapperName] = `./${customWrapperName}`;
1754
+ }
1755
+ this.generateConfigFile(compilation, compiler, `${name}/${baseCompName}`, compConfig);
989
1756
  this.generateTemplateFile(compilation, compiler, `${name}/${baseCompName}`, template.buildBaseComponentTemplate, this.options.fileType.templ);
990
1757
  }
991
1758
  this.generateConfigFile(compilation, compiler, `${name}/${customWrapperName}`, {
992
1759
  component: true,
993
- styleIsolation: 'apply-shared',
1760
+ styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
994
1761
  usingComponents: {
995
1762
  [customWrapperName]: `./${customWrapperName}`
996
1763
  }
@@ -1040,6 +1807,8 @@ class TaroMiniPlugin {
1040
1807
  const { modifyMiniConfigs } = combination.config;
1041
1808
  const baseTemplateName = 'base';
1042
1809
  const isUsingCustomWrapper = component_1.componentConfig.thirdPartyComponents.has('custom-wrapper');
1810
+ let subPackageIndieCustomWrapperRoots = new Set();
1811
+ compilation[subPackageIndieCustomWrapperRootsKey] = subPackageIndieCustomWrapperRoots;
1043
1812
  /**
1044
1813
  * 与原生小程序混写时解析模板与样式
1045
1814
  */
@@ -1059,12 +1828,14 @@ class TaroMiniPlugin {
1059
1828
  const appConfigName = node_path_1.default.basename(appConfigPath).replace(node_path_1.default.extname(appConfigPath), '');
1060
1829
  this.generateConfigFile(compilation, compiler, this.appEntry, this.filesConfig[appConfigName].content);
1061
1830
  }
1062
- if (!template.isSupportRecursive) {
1831
+ // 当配置了 mainPackageRoot 时,跳过根目录模板文件的生成
1832
+ const skipRootTemplates = this.hasSubPackageIndieMainPackageRoot() && this.options.newBlended;
1833
+ if (!template.isSupportRecursive && !skipRootTemplates) {
1063
1834
  // 如微信、QQ 不支持递归模版的小程序,需要使用自定义组件协助递归
1064
1835
  this.generateTemplateFile(compilation, compiler, baseCompName, template.buildBaseComponentTemplate, this.options.fileType.templ);
1065
1836
  const baseCompConfig = {
1066
1837
  component: true,
1067
- styleIsolation: 'apply-shared',
1838
+ styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1068
1839
  usingComponents: {
1069
1840
  [baseCompName]: `./${baseCompName}`
1070
1841
  }
@@ -1073,7 +1844,7 @@ class TaroMiniPlugin {
1073
1844
  baseCompConfig.usingComponents[customWrapperName] = `./${customWrapperName}`;
1074
1845
  this.generateConfigFile(compilation, compiler, customWrapperName, {
1075
1846
  component: true,
1076
- styleIsolation: 'apply-shared',
1847
+ styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1077
1848
  usingComponents: {
1078
1849
  [baseCompName]: `./${baseCompName}`,
1079
1850
  [customWrapperName]: `./${customWrapperName}`
@@ -1082,24 +1853,48 @@ class TaroMiniPlugin {
1082
1853
  }
1083
1854
  this.generateConfigFile(compilation, compiler, baseCompName, baseCompConfig);
1084
1855
  }
1085
- else {
1856
+ else if (!skipRootTemplates) {
1086
1857
  if (isUsingCustomWrapper) {
1087
1858
  this.generateConfigFile(compilation, compiler, customWrapperName, {
1088
1859
  component: true,
1089
- styleIsolation: 'apply-shared',
1860
+ styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1090
1861
  usingComponents: {
1091
1862
  [customWrapperName]: `./${customWrapperName}`
1092
1863
  }
1093
1864
  });
1094
1865
  }
1095
1866
  }
1096
- this.generateTemplateFile(compilation, compiler, baseTemplateName, template.buildTemplate, component_1.componentConfig);
1097
- isUsingCustomWrapper && this.generateTemplateFile(compilation, compiler, customWrapperName, template.buildCustomComponentTemplate, this.options.fileType.templ);
1098
- this.generateXSFile(compilation, compiler, 'utils');
1867
+ // 当配置了 mainPackageRoot 时,跳过根目录 base.wxml 和 utils.wxs 的生成
1868
+ if (!skipRootTemplates) {
1869
+ this.generateTemplateFile(compilation, compiler, baseTemplateName, template.buildTemplate, component_1.componentConfig);
1870
+ isUsingCustomWrapper && this.generateTemplateFile(compilation, compiler, customWrapperName, template.buildCustomComponentTemplate, this.options.fileType.templ);
1871
+ this.generateXSFile(compilation, compiler, 'utils');
1872
+ }
1873
+ // ★ 为子分包生成独立的模板文件(base.wxml, utils.wxs, comp.*, custom-wrapper.*)
1874
+ if (this.getSubPackageIndieConfigs().length && this.options.newBlended) {
1875
+ subPackageIndieCustomWrapperRoots = this.generateSubPackageIndieFiles(compilation, compiler, template, baseTemplateName);
1876
+ compilation[subPackageIndieCustomWrapperRootsKey] = subPackageIndieCustomWrapperRoots;
1877
+ // 注意:runtime chunks (app.js, app.wxss 等) 需要在 injectCommonStyles 之后生成,
1878
+ // 因为 injectCommonStyles 会修改 app.wxss 并创建 app-origin.wxss
1879
+ }
1099
1880
  this.components.forEach(component => {
1100
1881
  const importBaseTemplatePath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(component.path, node_path_1.default.join(sourceDir, isBuildPlugin ? 'plugin' : '', this.getTemplatePath(baseTemplateName))));
1101
1882
  const config = this.filesConfig[this.getConfigFilePath(component.name)];
1102
1883
  if (config) {
1884
+ const indieMatch = this.getSubPackageIndieMatch(component.name);
1885
+ if (indieMatch && !component.isNative) {
1886
+ const importBaseCompPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(component.path, node_path_1.default.join(sourceDir, indieMatch.root, this.getTargetFilePath(baseCompName, ''))));
1887
+ const importCustomWrapperPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(component.path, node_path_1.default.join(sourceDir, indieMatch.root, this.getTargetFilePath(customWrapperName, ''))));
1888
+ config.content.usingComponents = Object.assign({}, config.content.usingComponents);
1889
+ const isRootUsingCustomWrapper = subPackageIndieCustomWrapperRoots.has(indieMatch.root);
1890
+ const isRootRecursiveDisabled = this.isRecursiveComponentDisabledForRoot(indieMatch.root);
1891
+ if (isRootUsingCustomWrapper && !isRootRecursiveDisabled && !config.content.usingComponents[customWrapperName]) {
1892
+ config.content.usingComponents[customWrapperName] = importCustomWrapperPath;
1893
+ }
1894
+ if (!template.isSupportRecursive && !isRootRecursiveDisabled && !config.content.usingComponents[baseCompName]) {
1895
+ config.content.usingComponents[baseCompName] = importBaseCompPath;
1896
+ }
1897
+ }
1103
1898
  this.generateConfigFile(compilation, compiler, component.path, config.content);
1104
1899
  }
1105
1900
  if (!component.isNative) {
@@ -1107,7 +1902,17 @@ class TaroMiniPlugin {
1107
1902
  }
1108
1903
  });
1109
1904
  this.pages.forEach(page => {
1110
- const importBaseTemplatePath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, isBuildPlugin ? 'plugin' : '', this.getTemplatePath(baseTemplateName))));
1905
+ // 检查是否属于子分包独立模板的子分包
1906
+ const subPackageIndieRoot = this.isInSubPackageIndieRoot(page.name);
1907
+ let importBaseTemplatePath;
1908
+ if (subPackageIndieRoot) {
1909
+ // 子分包:引用本地的 base.wxml
1910
+ importBaseTemplatePath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, subPackageIndieRoot, this.getTemplatePath(baseTemplateName))));
1911
+ }
1912
+ else {
1913
+ // 主包/普通分包:引用根目录的 base.wxml
1914
+ importBaseTemplatePath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, isBuildPlugin ? 'plugin' : '', this.getTemplatePath(baseTemplateName))));
1915
+ }
1111
1916
  const config = this.filesConfig[this.getConfigFilePath(page.name)];
1112
1917
  // pages 里面会混合独立分包的,在这里需要过滤一下,避免重复生成 assets
1113
1918
  const isIndependent = !!this.getIndependentPackage(page.path);
@@ -1118,13 +1923,29 @@ class TaroMiniPlugin {
1118
1923
  this.generateTemplateFile(compilation, compiler, page.path, template.buildPageTemplate, importBaseTemplatePath, config);
1119
1924
  }
1120
1925
  if (config) {
1121
- const importBaseCompPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, isBuildPlugin ? 'plugin' : '', this.getTargetFilePath(baseCompName, ''))));
1122
- const importCustomWrapperPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, isBuildPlugin ? 'plugin' : '', this.getTargetFilePath(customWrapperName, ''))));
1926
+ let importBaseCompPath;
1927
+ let importCustomWrapperPath;
1928
+ if (subPackageIndieRoot) {
1929
+ // 子分包:引用本地的 comp 和 custom-wrapper
1930
+ importBaseCompPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, subPackageIndieRoot, this.getTargetFilePath(baseCompName, ''))));
1931
+ importCustomWrapperPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, subPackageIndieRoot, this.getTargetFilePath(customWrapperName, ''))));
1932
+ }
1933
+ else {
1934
+ // 主包:引用根目录
1935
+ importBaseCompPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, isBuildPlugin ? 'plugin' : '', this.getTargetFilePath(baseCompName, ''))));
1936
+ importCustomWrapperPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, isBuildPlugin ? 'plugin' : '', this.getTargetFilePath(customWrapperName, ''))));
1937
+ }
1123
1938
  config.content.usingComponents = Object.assign({}, config.content.usingComponents);
1124
- if (isUsingCustomWrapper) {
1939
+ const isPageRecursiveDisabled = subPackageIndieRoot
1940
+ ? this.isRecursiveComponentDisabledForRoot(subPackageIndieRoot)
1941
+ : false;
1942
+ const shouldUseCustomWrapper = subPackageIndieRoot
1943
+ ? subPackageIndieCustomWrapperRoots.has(subPackageIndieRoot) && !isPageRecursiveDisabled
1944
+ : isUsingCustomWrapper;
1945
+ if (shouldUseCustomWrapper) {
1125
1946
  config.content.usingComponents[customWrapperName] = importCustomWrapperPath;
1126
1947
  }
1127
- if (!template.isSupportRecursive && !page.isNative) {
1948
+ if (!template.isSupportRecursive && !page.isNative && !isPageRecursiveDisabled) {
1128
1949
  config.content.usingComponents[baseCompName] = importBaseCompPath;
1129
1950
  }
1130
1951
  this.generateConfigFile(compilation, compiler, page.path, config.content);
@@ -1132,6 +1953,10 @@ class TaroMiniPlugin {
1132
1953
  });
1133
1954
  this.generateTabBarFiles(compilation, compiler);
1134
1955
  this.injectCommonStyles(compilation, compiler);
1956
+ // ★ 为 mainPackageRoot 生成 runtime chunks(必须在 injectCommonStyles 之后,因为需要复制处理后的 app.wxss)
1957
+ if (this.hasSubPackageIndieMainPackageRoot() && this.options.newBlended) {
1958
+ this.generateMainPackageRuntimeFiles(compilation, compiler);
1959
+ }
1135
1960
  if (this.themeLocation) {
1136
1961
  this.generateDarkModeFile(compilation, compiler);
1137
1962
  }
@@ -1148,6 +1973,11 @@ class TaroMiniPlugin {
1148
1973
  optimizeMiniFiles(compilation, _compiler) {
1149
1974
  return __awaiter(this, void 0, void 0, function* () {
1150
1975
  const isUsingCustomWrapper = component_1.componentConfig.thirdPartyComponents.has('custom-wrapper');
1976
+ const shouldKeepRecursiveComponent = !this.options.template.isSupportRecursive || isUsingCustomWrapper;
1977
+ const hasSubPackageIndieCustomWrapperRoots = compilation[subPackageIndieCustomWrapperRootsKey] instanceof Set;
1978
+ const subPackageIndieCustomWrapperRoots = hasSubPackageIndieCustomWrapperRoots
1979
+ ? compilation[subPackageIndieCustomWrapperRootsKey]
1980
+ : new Set();
1151
1981
  /**
1152
1982
  * 与原生小程序混写时解析模板与样式
1153
1983
  */
@@ -1164,11 +1994,67 @@ class TaroMiniPlugin {
1164
1994
  delete compilation.assets[assetPath];
1165
1995
  }
1166
1996
  });
1997
+ if (this.options.newBlended) {
1998
+ this.getAllIndieRoots().forEach(root => {
1999
+ // ★ 禁用递归组件的 root,清理所有 comp/custom-wrapper/recursive-component 残留产物
2000
+ if (this.isRecursiveComponentDisabledForRoot(root)) {
2001
+ delete compilation.assets[`${root}/${baseCompName}.js`];
2002
+ delete compilation.assets[`${root}/${baseCompName}${this.options.fileType.config}`];
2003
+ delete compilation.assets[`${root}/${baseCompName}${this.options.fileType.templ}`];
2004
+ delete compilation.assets[`${root}/${customWrapperName}.js`];
2005
+ delete compilation.assets[`${root}/${customWrapperName}${this.options.fileType.config}`];
2006
+ delete compilation.assets[`${root}/${customWrapperName}${this.options.fileType.templ}`];
2007
+ delete compilation.assets[`${root}/${recursiveComponentName}.js`];
2008
+ return;
2009
+ }
2010
+ const isRootUsingCustomWrapper = hasSubPackageIndieCustomWrapperRoots
2011
+ ? subPackageIndieCustomWrapperRoots.has(root)
2012
+ : this.isSubPackageIndieRootUsingCustomWrapper(compilation, root, this.getScopedSubPackageIndieComponentConfig(compilation, root).thirdPartyComponents);
2013
+ if (isRootUsingCustomWrapper)
2014
+ return;
2015
+ delete compilation.assets[`${root}/${customWrapperName}.js`];
2016
+ delete compilation.assets[`${root}/${customWrapperName}${this.options.fileType.config}`];
2017
+ delete compilation.assets[`${root}/${customWrapperName}${this.options.fileType.templ}`];
2018
+ });
2019
+ }
2020
+ if (!shouldKeepRecursiveComponent && this.options.newBlended) {
2021
+ this.getAllIndieRoots().forEach(root => {
2022
+ delete compilation.assets[`${root}/${recursiveComponentName}.js`];
2023
+ });
2024
+ }
2025
+ // ★ 当配置了 mainPackageRoot 时,删除根目录的 runtime chunks
2026
+ const { newBlended, commonChunks, fileType } = this.options;
2027
+ if (this.hasSubPackageIndieMainPackageRoot() && newBlended) {
2028
+ const styleExt = fileType.style;
2029
+ const runtimeChunks = ['app', ...commonChunks];
2030
+ runtimeChunks.forEach(chunkName => {
2031
+ // 删除根目录 JS 文件
2032
+ delete compilation.assets[`${chunkName}.js`];
2033
+ // 删除根目录 wxss 文件
2034
+ delete compilation.assets[`${chunkName}${styleExt}`];
2035
+ });
2036
+ // 删除 app-origin.wxss
2037
+ delete compilation.assets[`app-origin${styleExt}`];
2038
+ // 删除根目录的 comp.js (由 addEntries 生成)
2039
+ delete compilation.assets[`${baseCompName}.js`];
2040
+ // 删除根目录的 custom-wrapper.js
2041
+ delete compilation.assets[`${customWrapperName}.js`];
2042
+ }
1167
2043
  });
1168
2044
  }
1169
2045
  generateConfigFile(compilation, compiler, filePath, config) {
1170
2046
  const { RawSource } = compiler.webpack.sources;
1171
2047
  const fileConfigName = this.getConfigPath(this.getComponentName(filePath));
2048
+ // ★ 为子分包独立模板的组件注入额外配置
2049
+ const componentName = this.getComponentName(filePath);
2050
+ const subPackageIndieRoot = this.isInSubPackageIndieRoot(componentName);
2051
+ if (subPackageIndieRoot && this.nativeComponents.has(componentName)) {
2052
+ const styleIsolation = this.options.template.isSupportRecursive
2053
+ ? STYLE_ISOLATION_APPLY_SHARED
2054
+ : STYLE_ISOLATION_SHARED;
2055
+ config.styleIsolation = config.styleIsolation || styleIsolation;
2056
+ config.isNewBlended = true;
2057
+ }
1172
2058
  const unofficialConfigs = ['enableShareAppMessage', 'enableShareTimeline', 'enablePageMeta', 'components'];
1173
2059
  unofficialConfigs.forEach(item => {
1174
2060
  delete config[item];
@@ -1177,6 +2063,21 @@ class TaroMiniPlugin {
1177
2063
  const fileConfigStr = JSON.stringify(config);
1178
2064
  compilation.assets[fileConfigName] = new RawSource(fileConfigStr);
1179
2065
  }
2066
+ generateSubPackageIndieScriptFile(compilation, compiler, filePath, content) {
2067
+ const { RawSource } = compiler.webpack.sources;
2068
+ compilation.assets[this.getTargetFilePath(filePath, '.js')] = new RawSource(content);
2069
+ }
2070
+ createRecursiveComponentWrapperSource(componentName) {
2071
+ const args = componentName ? JSON.stringify(componentName) : '';
2072
+ return `const registerRecursiveComponent = globalThis.__taroRegisterRecursiveComponent
2073
+
2074
+ if (typeof registerRecursiveComponent !== 'function') {
2075
+ throw new Error('globalThis.__taroRegisterRecursiveComponent is not a function')
2076
+ }
2077
+
2078
+ registerRecursiveComponent(${args})
2079
+ `;
2080
+ }
1180
2081
  generateTemplateFile(compilation, compiler, filePath, templateFn, ...options) {
1181
2082
  var _a;
1182
2083
  const { RawSource } = compiler.webpack.sources;
@@ -1315,12 +2216,18 @@ class TaroMiniPlugin {
1315
2216
  });
1316
2217
  });
1317
2218
  }
1318
- if (commons.size() > 0) {
2219
+ // 判断是否需要处理样式:有 common chunks 或者有 app.wxss
2220
+ const hasMainPackageRoot = this.hasSubPackageIndieMainPackageRoot() && newBlended;
2221
+ const hasAppStyle = !!assets[appStyle];
2222
+ const shouldProcessStyles = commons.size() > 0 || (hasMainPackageRoot && hasAppStyle);
2223
+ if (shouldProcessStyles) {
1319
2224
  const APP_STYLE_NAME = 'app-origin' + styleExt;
1320
2225
  assets[APP_STYLE_NAME] = new ConcatSource(originSource);
1321
2226
  const source = new ConcatSource('');
1322
2227
  source.add(`@import ${JSON.stringify((0, loader_utils_1.urlToRequest)(APP_STYLE_NAME))};`);
1323
- source.add(commons);
2228
+ if (commons.size() > 0) {
2229
+ source.add(commons);
2230
+ }
1324
2231
  source.add('\n');
1325
2232
  assets[appStyle] = source;
1326
2233
  if (newBlended) {
@@ -1329,6 +2236,7 @@ class TaroMiniPlugin {
1329
2236
  if (page.isNative)
1330
2237
  return;
1331
2238
  const pageStyle = `${page.name}${styleExt}`;
2239
+ const indieMatch = this.getSubPackageIndieMatch(page.name);
1332
2240
  if (this.nativeComponents.has(page.name)) {
1333
2241
  // 本地化组件如果没有wxss则直接写入一个空的
1334
2242
  if (!(pageStyle in assets)) {
@@ -1336,14 +2244,39 @@ class TaroMiniPlugin {
1336
2244
  }
1337
2245
  const source = new ConcatSource('');
1338
2246
  const originSource = assets[pageStyle];
1339
- componentCommons.forEach(item => {
1340
- source.add(`@import ${JSON.stringify((0, loader_utils_1.urlToRequest)(node_path_1.default.posix.relative(node_path_1.default.dirname(pageStyle), item)))};\n`);
1341
- });
2247
+ // 检查组件是否属于 subPackageIndie 分包
2248
+ if (indieMatch) {
2249
+ if (indieMatch.isMainPackageRoot) {
2250
+ // mainPackageRoot 下的入口组件:只需引用 ./app.wxss(它已包含 common.wxss 等)
2251
+ source.add(`@import ${JSON.stringify((0, loader_utils_1.urlToRequest)('./app' + styleExt))};\n`);
2252
+ }
2253
+ // subPackageRoots 下的子分包组件:不注入公共样式引用
2254
+ // 通过 styleIsolation: "apply-shared" 继承入口组件的样式
2255
+ }
2256
+ else {
2257
+ // 非 subPackageIndie 分包:引用根目录的公共样式
2258
+ componentCommons.forEach(item => {
2259
+ source.add(`@import ${JSON.stringify((0, loader_utils_1.urlToRequest)(node_path_1.default.posix.relative(node_path_1.default.dirname(pageStyle), item)))};\n`);
2260
+ });
2261
+ }
1342
2262
  source.add(originSource);
1343
2263
  assets[pageStyle] = source;
1344
2264
  }
1345
2265
  else {
1346
- if (pageStyle in assets) {
2266
+ // 普通页面(非本地化组件)
2267
+ if (indieMatch === null || indieMatch === void 0 ? void 0 : indieMatch.isMainPackageRoot) {
2268
+ // mainPackageRoot 下的页面:只需 @import './app.wxss'(它已包含 common.wxss 等)
2269
+ const source = new ConcatSource('');
2270
+ if (pageStyle in assets) {
2271
+ source.add(assets[pageStyle]);
2272
+ }
2273
+ // 创建或更新样式文件,添加 app.wxss 引用
2274
+ const importSource = new ConcatSource('');
2275
+ importSource.add(`@import ${JSON.stringify((0, loader_utils_1.urlToRequest)('./app' + styleExt))};\n`);
2276
+ importSource.add(source);
2277
+ assets[pageStyle] = importSource;
2278
+ }
2279
+ else if (pageStyle in assets) {
1347
2280
  const source = new ConcatSource('');
1348
2281
  const originSource = assets[pageStyle];
1349
2282
  source.add(`@import ${JSON.stringify((0, loader_utils_1.urlToRequest)(node_path_1.default.posix.relative(node_path_1.default.dirname(pageStyle), 'app' + styleExt)))};\n`);