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

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.
@@ -1,4 +1,27 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
2
25
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
26
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
27
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -12,26 +35,27 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
36
  };
14
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
+ exports.STYLE_ISOLATION_SHARED = exports.STYLE_ISOLATION_APPLY_SHARED = exports.customWrapperName = exports.baseCompName = void 0;
15
39
  const node_path_1 = __importDefault(require("node:path"));
16
40
  const helper_1 = require("@tarojs/helper");
17
41
  const loader_utils_1 = require("loader-utils");
42
+ const tapable_1 = require("tapable");
18
43
  const EntryDependency_1 = __importDefault(require("webpack/lib/dependencies/EntryDependency"));
19
44
  const TaroSingleEntryDependency_1 = __importDefault(require("../dependencies/TaroSingleEntryDependency"));
20
45
  const prerender_1 = require("../prerender/prerender");
21
46
  const component_1 = require("../utils/component");
47
+ const forceCustomWrapper_1 = require("../utils/forceCustomWrapper");
22
48
  const webpack_1 = require("../utils/webpack");
49
+ const SubPackageIndiePlugin_1 = __importStar(require("./SubPackageIndiePlugin"));
23
50
  const TaroLoadChunksPlugin_1 = __importDefault(require("./TaroLoadChunksPlugin"));
24
51
  const TaroNormalModulesPlugin_1 = __importDefault(require("./TaroNormalModulesPlugin"));
25
52
  const TaroSingleEntryPlugin_1 = __importDefault(require("./TaroSingleEntryPlugin"));
26
- const baseCompName = 'comp';
27
- const customWrapperName = 'custom-wrapper';
28
- const subPackageIndieCustomWrapperRootsKey = '__taroSubPackageIndieCustomWrapperRoots';
29
- const recursiveComponentName = 'recursive-component';
53
+ exports.baseCompName = 'comp';
54
+ exports.customWrapperName = 'custom-wrapper';
30
55
  const PLUGIN_NAME = 'TaroMiniPlugin';
31
56
  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';
57
+ exports.STYLE_ISOLATION_APPLY_SHARED = 'apply-shared';
58
+ exports.STYLE_ISOLATION_SHARED = 'shared';
35
59
  function isLoaderExist(loaders, loaderName) {
36
60
  return loaders.some(item => item.loader === loaderName);
37
61
  }
@@ -51,7 +75,7 @@ class TaroMiniPlugin {
51
75
  this.dependencies = new Map();
52
76
  this.pageLoaderName = '@tarojs/taro-loader/lib/page';
53
77
  this.independentPackages = new Map();
54
- this.moduleRequestMap = new Map();
78
+ this.subPackageIndiePlugin = null;
55
79
  const { combination } = options;
56
80
  const miniBuildConfig = combination.config;
57
81
  const { template, baseLevel = 16, experimental } = miniBuildConfig;
@@ -75,6 +99,22 @@ class TaroMiniPlugin {
75
99
  hot: options.hot,
76
100
  loaderMeta: options.loaderMeta || {},
77
101
  };
102
+ // 初始化扩展钩子
103
+ this.hooks = {
104
+ modifyEntries: new tapable_1.SyncWaterfallHook(['entries']),
105
+ modifyChunkRequire: new tapable_1.SyncWaterfallHook(['result', 'chunkId', 'miniType']),
106
+ afterResolveModule: new tapable_1.SyncHook(['resolveData']),
107
+ compileExtraEntries: new tapable_1.SyncHook(['compiler', 'compilation', 'promises']),
108
+ modifySkipRootTemplates: new tapable_1.SyncWaterfallHook(['skip']),
109
+ generateExtraFiles: new tapable_1.SyncWaterfallHook(['customWrapperRoots', 'compilation', 'compiler']),
110
+ modifyPageConfig: new tapable_1.SyncWaterfallHook(['context', 'page', 'customWrapperRoots']),
111
+ modifyComponentConfig: new tapable_1.SyncHook(['context', 'customWrapperRoots']),
112
+ afterGenerateFiles: new tapable_1.SyncHook(['compilation', 'compiler']),
113
+ optimizeAssets: new tapable_1.SyncHook(['compilation']),
114
+ modifyConfig: new tapable_1.SyncWaterfallHook(['config', 'componentName']),
115
+ modifyStyleImport: new tapable_1.SyncWaterfallHook(['context', 'page']),
116
+ modifyShouldProcessStyles: new tapable_1.SyncWaterfallHook(['shouldProcess']),
117
+ };
78
118
  if (template.isSupportRecursive === false && baseLevel > 0) {
79
119
  template.baseLevel = baseLevel;
80
120
  }
@@ -105,11 +145,16 @@ class TaroMiniPlugin {
105
145
  apply(compiler) {
106
146
  this.context = compiler.context;
107
147
  this.appEntry = this.getAppEntry(compiler);
148
+ if (this.options.newBlended) {
149
+ this.subPackageIndiePlugin = new SubPackageIndiePlugin_1.default(this);
150
+ this.subPackageIndiePlugin.apply();
151
+ }
108
152
  const { commonChunks, combination, framework, isBuildPlugin, newBlended, } = this.options;
109
153
  const { addChunkPages, onCompilerMake, modifyBuildAssets, onParseCreateElement, } = combination.config;
110
154
  /** build mode */
111
155
  compiler.hooks.run.tapAsync(PLUGIN_NAME, this.tryAsync((compiler) => __awaiter(this, void 0, void 0, function* () {
112
156
  yield this.run(compiler);
157
+ this.applyForceCustomWrapperDefine(compiler);
113
158
  new TaroLoadChunksPlugin_1.default({
114
159
  commonChunks: commonChunks,
115
160
  isBuildPlugin,
@@ -125,6 +170,7 @@ class TaroMiniPlugin {
125
170
  this.isWatch = true;
126
171
  }
127
172
  yield this.run(compiler);
173
+ this.applyForceCustomWrapperDefine(compiler);
128
174
  if (!this.loadChunksPlugin) {
129
175
  this.loadChunksPlugin = new TaroLoadChunksPlugin_1.default({
130
176
  commonChunks: commonChunks,
@@ -141,7 +187,7 @@ class TaroMiniPlugin {
141
187
  const dependencies = this.dependencies;
142
188
  const promises = [];
143
189
  this.compileIndependentPages(compiler, compilation, dependencies, promises);
144
- this.compileSubPackageIndieStandaloneEntries(compiler, compilation, promises);
190
+ this.hooks.compileExtraEntries.call(compiler, compilation, promises);
145
191
  dependencies.forEach(dep => {
146
192
  promises.push(new Promise((resolve, reject) => {
147
193
  compilation.addEntry(this.options.sourceDir, dep, Object.assign({ name: dep.name }, dep.options), err => err ? reject(err) : resolve(null));
@@ -156,40 +202,7 @@ class TaroMiniPlugin {
156
202
  compilation.dependencyFactories.set(TaroSingleEntryDependency_1.default, normalModuleFactory);
157
203
  if (this.options.newBlended) {
158
204
  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
- });
205
+ this.hooks.afterResolveModule.call(resolveData);
193
206
  });
194
207
  }
195
208
  /**
@@ -270,8 +283,6 @@ class TaroMiniPlugin {
270
283
  name: PLUGIN_NAME,
271
284
  stage: PROCESS_ASSETS_STAGE_ADDITIONAL
272
285
  }, this.tryAsync(() => __awaiter(this, void 0, void 0, function* () {
273
- if (compilation.__tag === SUBPACKAGE_STANDALONE_CHILD_TAG)
274
- return;
275
286
  // 如果是子编译器,证明是编译独立分包,进行单独的处理
276
287
  if (compilation.__tag === CHILD_COMPILER_TAG) {
277
288
  yield this.generateIndependentMiniFiles(compilation, compiler);
@@ -286,8 +297,6 @@ class TaroMiniPlugin {
286
297
  // Stage 触发顺序:https://webpack.js.org/api/compilation-hooks/#list-of-asset-processing-stages
287
298
  stage: PROCESS_ASSETS_STAGE_OPTIMIZE
288
299
  }, this.tryAsync(() => __awaiter(this, void 0, void 0, function* () {
289
- if (compilation.__tag === SUBPACKAGE_STANDALONE_CHILD_TAG)
290
- return;
291
300
  yield this.optimizeMiniFiles(compilation, compiler);
292
301
  })));
293
302
  compilation.hooks.processAssets.tapAsync({
@@ -295,8 +304,6 @@ class TaroMiniPlugin {
295
304
  // 该 stage 是最后执行的,确保 taro 暴露给用户的钩子 modifyBuildAssets 在内部处理完 assets 之后再调用
296
305
  stage: PROCESS_ASSETS_STAGE_REPORT
297
306
  }, this.tryAsync(() => __awaiter(this, void 0, void 0, function* () {
298
- if (compilation.__tag === SUBPACKAGE_STANDALONE_CHILD_TAG)
299
- return;
300
307
  if (typeof modifyBuildAssets === 'function') {
301
308
  yield modifyBuildAssets(compilation.assets, this);
302
309
  }
@@ -341,15 +348,13 @@ class TaroMiniPlugin {
341
348
  let source;
342
349
  const id = (0, webpack_1.getChunkIdOrName)(chunk);
343
350
  const { miniType } = entryModule;
351
+ const modifyResult = this.hooks.modifyChunkRequire.call({ source: modules, handled: false }, id, miniType);
352
+ if (modifyResult === null || modifyResult === void 0 ? void 0 : modifyResult.handled) {
353
+ return modifyResult.source;
354
+ }
344
355
  const entryChunk = [{ name: 'app' }];
345
356
  // 所有模块都依赖app.js,确保@tarojs\plugin-platform-xxx\dist\runtime.js先于@tarojs/runtime执行,避免Taro API未被初始化
346
357
  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
- }
353
358
  fileChunks.forEach((v, k) => {
354
359
  if (k === id) {
355
360
  source = (0, webpack_1.addRequireToSource)(id, modules, v);
@@ -359,12 +364,6 @@ class TaroMiniPlugin {
359
364
  return source || modules;
360
365
  }
361
366
  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
- }
368
367
  return (0, webpack_1.addRequireToSource)(id, modules, entryChunk);
369
368
  }
370
369
  }
@@ -541,12 +540,12 @@ class TaroMiniPlugin {
541
540
  }
542
541
  if (!this.options.template.isSupportRecursive) {
543
542
  pluginJSON.publicComponents = Object.assign({}, publicComponents, {
544
- [baseCompName]: baseCompName
543
+ [exports.baseCompName]: exports.baseCompName
545
544
  });
546
545
  }
547
546
  if (isUsingCustomWrapper) {
548
547
  pluginJSON.publicComponents = Object.assign({}, publicComponents, {
549
- [customWrapperName]: customWrapperName
548
+ [exports.customWrapperName]: exports.customWrapperName
550
549
  });
551
550
  }
552
551
  }
@@ -634,113 +633,6 @@ class TaroMiniPlugin {
634
633
  this.nativeComponents.set(item, componentObj);
635
634
  });
636
635
  }
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
- }
744
636
  /**
745
637
  * 读取页面及其依赖的组件的配置
746
638
  */
@@ -803,14 +695,16 @@ class TaroMiniPlugin {
803
695
  * 在 this.dependencies 中新增或修改 app、模板组件、页面、组件等资源模块
804
696
  */
805
697
  addEntries() {
806
- const { template, newBlended } = this.options;
698
+ const { template } = this.options;
807
699
  this.addEntry(this.appEntry, 'app', helper_1.META_TYPE.ENTRY);
808
- // 当配置了 mainPackageRoot 时,跳过根目录 comp 和 custom-wrapper 入口
809
- const skipRootEntries = this.hasSubPackageIndieMainPackageRoot() && newBlended;
810
- if (!template.isSupportRecursive && !skipRootEntries) {
700
+ const entryFlags = this.hooks.modifyEntries.call({
701
+ skipRootComp: false,
702
+ skipRootWrapper: false,
703
+ });
704
+ if (!template.isSupportRecursive && !entryFlags.skipRootComp) {
811
705
  this.addEntry(node_path_1.default.resolve(__dirname, '..', 'template/comp'), 'comp', helper_1.META_TYPE.STATIC);
812
706
  }
813
- if (!skipRootEntries) {
707
+ if (!entryFlags.skipRootWrapper) {
814
708
  this.addEntry(node_path_1.default.resolve(__dirname, '..', 'template/custom-wrapper'), 'custom-wrapper', helper_1.META_TYPE.STATIC);
815
709
  }
816
710
  // subPackageIndie 下的 comp/custom-wrapper 统一走独立子编译器,避免被主编译的公共 chunk 共享
@@ -843,6 +737,34 @@ class TaroMiniPlugin {
843
737
  }
844
738
  });
845
739
  }
740
+ computeForceCustomWrapperForWebpackMainComp() {
741
+ var _a;
742
+ if (this.options.template.isSupportRecursive)
743
+ return false;
744
+ const independentPaths = new Set();
745
+ this.independentPackages.forEach(({ pages }) => {
746
+ pages.forEach(p => independentPaths.add(p));
747
+ });
748
+ for (const page of this.pages) {
749
+ if (page.isNative || independentPaths.has(page.path))
750
+ continue;
751
+ const content = (_a = this.filesConfig[this.getConfigFilePath(page.name)]) === null || _a === void 0 ? void 0 : _a.content;
752
+ if (content === null || content === void 0 ? void 0 : content.forceCustomWrapper)
753
+ return true;
754
+ }
755
+ return false;
756
+ }
757
+ computeForceCustomWrapperForIndieRoot(pages) {
758
+ return (0, forceCustomWrapper_1.computeForceCustomWrapperForIndependentPackage)(pages, this.pages, this.filesConfig, (p) => this.getConfigFilePath(p));
759
+ }
760
+ applyForceCustomWrapperDefine(compiler) {
761
+ if (this.options.template.isSupportRecursive)
762
+ return;
763
+ const value = this.computeForceCustomWrapperForWebpackMainComp();
764
+ new compiler.webpack.DefinePlugin({
765
+ TARO_FORCE_CUSTOM_WRAPPER: JSON.stringify(value)
766
+ }).apply(compiler);
767
+ }
846
768
  replaceExt(file, ext) {
847
769
  return node_path_1.default.join(node_path_1.default.dirname(file), node_path_1.default.basename(file, node_path_1.default.extname(file)) + `${ext}`);
848
770
  }
@@ -1002,7 +924,7 @@ class TaroMiniPlugin {
1002
924
  filename: `[name]${this.options.fileType.style}`,
1003
925
  chunkFilename: `[name]${this.options.fileType.style}`
1004
926
  }).apply(childCompiler);
1005
- new compiler.webpack.DefinePlugin(this.options.constantsReplaceList).apply(childCompiler);
927
+ new compiler.webpack.DefinePlugin(Object.assign(Object.assign({}, this.options.constantsReplaceList), { TARO_FORCE_CUSTOM_WRAPPER: JSON.stringify(this.computeForceCustomWrapperForIndieRoot(pages)) })).apply(childCompiler);
1006
928
  if (compiler.options.optimization) {
1007
929
  new SplitChunksPlugin({
1008
930
  chunks: 'all',
@@ -1079,45 +1001,6 @@ class TaroMiniPlugin {
1079
1001
  });
1080
1002
  }
1081
1003
  }
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
- }
1121
1004
  /**
1122
1005
  * 搜集 tabbar icon 图标路径
1123
1006
  * 收集自定义 tabbar 组件
@@ -1186,546 +1069,6 @@ class TaroMiniPlugin {
1186
1069
  return;
1187
1070
  thirdPartyComponents.set(componentName, new Set(attrs));
1188
1071
  }
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
- }
1729
1072
  /** 生成小程序独立分包的相关文件 */
1730
1073
  generateIndependentMiniFiles(compilation, compiler) {
1731
1074
  return __awaiter(this, void 0, void 0, function* () {
@@ -1744,25 +1087,25 @@ class TaroMiniPlugin {
1744
1087
  // 如微信、QQ 不支持递归模版的小程序,需要使用自定义组件协助递归
1745
1088
  const compConfig = {
1746
1089
  component: true,
1747
- styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1090
+ styleIsolation: exports.STYLE_ISOLATION_APPLY_SHARED,
1748
1091
  usingComponents: {
1749
- [baseCompName]: `./${baseCompName}`
1092
+ [exports.baseCompName]: `./${exports.baseCompName}`
1750
1093
  }
1751
1094
  };
1752
1095
  if (isUsingCustomWrapper) {
1753
- compConfig.usingComponents[customWrapperName] = `./${customWrapperName}`;
1096
+ compConfig.usingComponents[exports.customWrapperName] = `./${exports.customWrapperName}`;
1754
1097
  }
1755
- this.generateConfigFile(compilation, compiler, `${name}/${baseCompName}`, compConfig);
1756
- this.generateTemplateFile(compilation, compiler, `${name}/${baseCompName}`, template.buildBaseComponentTemplate, this.options.fileType.templ);
1098
+ this.generateConfigFile(compilation, compiler, `${name}/${exports.baseCompName}`, compConfig);
1099
+ this.generateTemplateFile(compilation, compiler, `${name}/${exports.baseCompName}`, template.buildBaseComponentTemplate, this.options.fileType.templ);
1757
1100
  }
1758
- this.generateConfigFile(compilation, compiler, `${name}/${customWrapperName}`, {
1101
+ this.generateConfigFile(compilation, compiler, `${name}/${exports.customWrapperName}`, {
1759
1102
  component: true,
1760
- styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1103
+ styleIsolation: exports.STYLE_ISOLATION_APPLY_SHARED,
1761
1104
  usingComponents: {
1762
- [customWrapperName]: `./${customWrapperName}`
1105
+ [exports.customWrapperName]: `./${exports.customWrapperName}`
1763
1106
  }
1764
1107
  });
1765
- this.generateTemplateFile(compilation, compiler, `${name}/${customWrapperName}`, template.buildCustomComponentTemplate, this.options.fileType.templ);
1108
+ this.generateTemplateFile(compilation, compiler, `${name}/${exports.customWrapperName}`, template.buildCustomComponentTemplate, this.options.fileType.templ);
1766
1109
  this.generateXSFile(compilation, compiler, `${name}/utils`);
1767
1110
  });
1768
1111
  this.pages.forEach(page => {
@@ -1785,14 +1128,14 @@ class TaroMiniPlugin {
1785
1128
  this.generateTemplateFile(compilation, compiler, page.path, template.buildPageTemplate, importBaseTemplatePath, config);
1786
1129
  }
1787
1130
  if (config) {
1788
- const importBaseCompPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, independentName, this.getTargetFilePath(baseCompName, ''))));
1789
- const importCustomWrapperPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, independentName, this.getTargetFilePath(customWrapperName, ''))));
1131
+ const importBaseCompPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, independentName, this.getTargetFilePath(exports.baseCompName, ''))));
1132
+ const importCustomWrapperPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, independentName, this.getTargetFilePath(exports.customWrapperName, ''))));
1790
1133
  config.content.usingComponents = Object.assign({}, config.content.usingComponents);
1791
1134
  if (isUsingCustomWrapper) {
1792
- config.content.usingComponents[customWrapperName] = importCustomWrapperPath;
1135
+ config.content.usingComponents[exports.customWrapperName] = importCustomWrapperPath;
1793
1136
  }
1794
1137
  if (!template.isSupportRecursive && !page.isNative) {
1795
- config.content.usingComponents[baseCompName] = importBaseCompPath;
1138
+ config.content.usingComponents[exports.baseCompName] = importBaseCompPath;
1796
1139
  }
1797
1140
  this.generateConfigFile(compilation, compiler, page.path, config.content);
1798
1141
  }
@@ -1808,7 +1151,7 @@ class TaroMiniPlugin {
1808
1151
  const baseTemplateName = 'base';
1809
1152
  const isUsingCustomWrapper = component_1.componentConfig.thirdPartyComponents.has('custom-wrapper');
1810
1153
  let subPackageIndieCustomWrapperRoots = new Set();
1811
- compilation[subPackageIndieCustomWrapperRootsKey] = subPackageIndieCustomWrapperRoots;
1154
+ compilation[SubPackageIndiePlugin_1.subPackageIndieCustomWrapperRootsKey] = subPackageIndieCustomWrapperRoots;
1812
1155
  /**
1813
1156
  * 与原生小程序混写时解析模板与样式
1814
1157
  */
@@ -1828,38 +1171,38 @@ class TaroMiniPlugin {
1828
1171
  const appConfigName = node_path_1.default.basename(appConfigPath).replace(node_path_1.default.extname(appConfigPath), '');
1829
1172
  this.generateConfigFile(compilation, compiler, this.appEntry, this.filesConfig[appConfigName].content);
1830
1173
  }
1831
- // 当配置了 mainPackageRoot 时,跳过根目录模板文件的生成
1832
- const skipRootTemplates = this.hasSubPackageIndieMainPackageRoot() && this.options.newBlended;
1174
+ let skipRootTemplates = false;
1175
+ skipRootTemplates = this.hooks.modifySkipRootTemplates.call(skipRootTemplates);
1833
1176
  if (!template.isSupportRecursive && !skipRootTemplates) {
1834
1177
  // 如微信、QQ 不支持递归模版的小程序,需要使用自定义组件协助递归
1835
- this.generateTemplateFile(compilation, compiler, baseCompName, template.buildBaseComponentTemplate, this.options.fileType.templ);
1178
+ this.generateTemplateFile(compilation, compiler, exports.baseCompName, template.buildBaseComponentTemplate, this.options.fileType.templ);
1836
1179
  const baseCompConfig = {
1837
1180
  component: true,
1838
- styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1181
+ styleIsolation: exports.STYLE_ISOLATION_APPLY_SHARED,
1839
1182
  usingComponents: {
1840
- [baseCompName]: `./${baseCompName}`
1183
+ [exports.baseCompName]: `./${exports.baseCompName}`
1841
1184
  }
1842
1185
  };
1843
1186
  if (isUsingCustomWrapper) {
1844
- baseCompConfig.usingComponents[customWrapperName] = `./${customWrapperName}`;
1845
- this.generateConfigFile(compilation, compiler, customWrapperName, {
1187
+ baseCompConfig.usingComponents[exports.customWrapperName] = `./${exports.customWrapperName}`;
1188
+ this.generateConfigFile(compilation, compiler, exports.customWrapperName, {
1846
1189
  component: true,
1847
- styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1190
+ styleIsolation: exports.STYLE_ISOLATION_APPLY_SHARED,
1848
1191
  usingComponents: {
1849
- [baseCompName]: `./${baseCompName}`,
1850
- [customWrapperName]: `./${customWrapperName}`
1192
+ [exports.baseCompName]: `./${exports.baseCompName}`,
1193
+ [exports.customWrapperName]: `./${exports.customWrapperName}`
1851
1194
  }
1852
1195
  });
1853
1196
  }
1854
- this.generateConfigFile(compilation, compiler, baseCompName, baseCompConfig);
1197
+ this.generateConfigFile(compilation, compiler, exports.baseCompName, baseCompConfig);
1855
1198
  }
1856
1199
  else if (!skipRootTemplates) {
1857
1200
  if (isUsingCustomWrapper) {
1858
- this.generateConfigFile(compilation, compiler, customWrapperName, {
1201
+ this.generateConfigFile(compilation, compiler, exports.customWrapperName, {
1859
1202
  component: true,
1860
- styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1203
+ styleIsolation: exports.STYLE_ISOLATION_APPLY_SHARED,
1861
1204
  usingComponents: {
1862
- [customWrapperName]: `./${customWrapperName}`
1205
+ [exports.customWrapperName]: `./${exports.customWrapperName}`
1863
1206
  }
1864
1207
  });
1865
1208
  }
@@ -1867,34 +1210,16 @@ class TaroMiniPlugin {
1867
1210
  // ★ 当配置了 mainPackageRoot 时,跳过根目录 base.wxml 和 utils.wxs 的生成
1868
1211
  if (!skipRootTemplates) {
1869
1212
  this.generateTemplateFile(compilation, compiler, baseTemplateName, template.buildTemplate, component_1.componentConfig);
1870
- isUsingCustomWrapper && this.generateTemplateFile(compilation, compiler, customWrapperName, template.buildCustomComponentTemplate, this.options.fileType.templ);
1213
+ isUsingCustomWrapper && this.generateTemplateFile(compilation, compiler, exports.customWrapperName, template.buildCustomComponentTemplate, this.options.fileType.templ);
1871
1214
  this.generateXSFile(compilation, compiler, 'utils');
1872
1215
  }
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
- }
1216
+ subPackageIndieCustomWrapperRoots = this.hooks.generateExtraFiles.call(subPackageIndieCustomWrapperRoots, compilation, compiler);
1217
+ compilation[SubPackageIndiePlugin_1.subPackageIndieCustomWrapperRootsKey] = subPackageIndieCustomWrapperRoots;
1880
1218
  this.components.forEach(component => {
1881
1219
  const importBaseTemplatePath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(component.path, node_path_1.default.join(sourceDir, isBuildPlugin ? 'plugin' : '', this.getTemplatePath(baseTemplateName))));
1882
1220
  const config = this.filesConfig[this.getConfigFilePath(component.name)];
1883
1221
  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
- }
1222
+ this.hooks.modifyComponentConfig.call({ config, component }, subPackageIndieCustomWrapperRoots);
1898
1223
  this.generateConfigFile(compilation, compiler, component.path, config.content);
1899
1224
  }
1900
1225
  if (!component.isNative) {
@@ -1902,61 +1227,46 @@ class TaroMiniPlugin {
1902
1227
  }
1903
1228
  });
1904
1229
  this.pages.forEach(page => {
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
- }
1230
+ let importBaseTemplatePath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, isBuildPlugin ? 'plugin' : '', this.getTemplatePath(baseTemplateName))));
1916
1231
  const config = this.filesConfig[this.getConfigFilePath(page.name)];
1917
1232
  // pages 里面会混合独立分包的,在这里需要过滤一下,避免重复生成 assets
1918
1233
  const isIndependent = !!this.getIndependentPackage(page.path);
1919
1234
  if (isIndependent)
1920
1235
  return;
1921
1236
  // 生成页面模板需要在生成页面配置之前,因为会依赖到页面配置的部分内容
1237
+ let importBaseCompPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, isBuildPlugin ? 'plugin' : '', this.getTargetFilePath(exports.baseCompName, ''))));
1238
+ let importCustomWrapperPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, isBuildPlugin ? 'plugin' : '', this.getTargetFilePath(exports.customWrapperName, ''))));
1239
+ let isPageRecursiveDisabled = false;
1240
+ let shouldUseCustomWrapper = isUsingCustomWrapper;
1241
+ const pageConfigContext = this.hooks.modifyPageConfig.call({
1242
+ importBaseTemplatePath,
1243
+ importBaseCompPath,
1244
+ importCustomWrapperPath,
1245
+ shouldUseCustomWrapper,
1246
+ isPageRecursiveDisabled,
1247
+ }, page, subPackageIndieCustomWrapperRoots);
1248
+ importBaseTemplatePath = pageConfigContext.importBaseTemplatePath;
1249
+ importBaseCompPath = pageConfigContext.importBaseCompPath;
1250
+ importCustomWrapperPath = pageConfigContext.importCustomWrapperPath;
1251
+ shouldUseCustomWrapper = pageConfigContext.shouldUseCustomWrapper;
1252
+ isPageRecursiveDisabled = pageConfigContext.isPageRecursiveDisabled;
1922
1253
  if (!page.isNative) {
1923
1254
  this.generateTemplateFile(compilation, compiler, page.path, template.buildPageTemplate, importBaseTemplatePath, config);
1924
1255
  }
1925
1256
  if (config) {
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
- }
1938
1257
  config.content.usingComponents = Object.assign({}, config.content.usingComponents);
1939
- const isPageRecursiveDisabled = subPackageIndieRoot
1940
- ? this.isRecursiveComponentDisabledForRoot(subPackageIndieRoot)
1941
- : false;
1942
- const shouldUseCustomWrapper = subPackageIndieRoot
1943
- ? subPackageIndieCustomWrapperRoots.has(subPackageIndieRoot) && !isPageRecursiveDisabled
1944
- : isUsingCustomWrapper;
1945
1258
  if (shouldUseCustomWrapper) {
1946
- config.content.usingComponents[customWrapperName] = importCustomWrapperPath;
1259
+ config.content.usingComponents[exports.customWrapperName] = importCustomWrapperPath;
1947
1260
  }
1948
1261
  if (!template.isSupportRecursive && !page.isNative && !isPageRecursiveDisabled) {
1949
- config.content.usingComponents[baseCompName] = importBaseCompPath;
1262
+ config.content.usingComponents[exports.baseCompName] = importBaseCompPath;
1950
1263
  }
1951
1264
  this.generateConfigFile(compilation, compiler, page.path, config.content);
1952
1265
  }
1953
1266
  });
1954
1267
  this.generateTabBarFiles(compilation, compiler);
1955
1268
  this.injectCommonStyles(compilation, compiler);
1956
- // ★ 为 mainPackageRoot 生成 runtime chunks(必须在 injectCommonStyles 之后,因为需要复制处理后的 app.wxss)
1957
- if (this.hasSubPackageIndieMainPackageRoot() && this.options.newBlended) {
1958
- this.generateMainPackageRuntimeFiles(compilation, compiler);
1959
- }
1269
+ this.hooks.afterGenerateFiles.call(compilation, compiler);
1960
1270
  if (this.themeLocation) {
1961
1271
  this.generateDarkModeFile(compilation, compiler);
1962
1272
  }
@@ -1973,11 +1283,6 @@ class TaroMiniPlugin {
1973
1283
  optimizeMiniFiles(compilation, _compiler) {
1974
1284
  return __awaiter(this, void 0, void 0, function* () {
1975
1285
  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();
1981
1286
  /**
1982
1287
  * 与原生小程序混写时解析模板与样式
1983
1288
  */
@@ -1994,68 +1299,15 @@ class TaroMiniPlugin {
1994
1299
  delete compilation.assets[assetPath];
1995
1300
  }
1996
1301
  });
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
- }
1302
+ this.hooks.optimizeAssets.call(compilation);
2043
1303
  });
2044
1304
  }
2045
1305
  generateConfigFile(compilation, compiler, filePath, config) {
2046
1306
  const { RawSource } = compiler.webpack.sources;
2047
1307
  const fileConfigName = this.getConfigPath(this.getComponentName(filePath));
2048
- // ★ 为子分包独立模板的组件注入额外配置
2049
1308
  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
- }
2058
- const unofficialConfigs = ['enableShareAppMessage', 'enableShareTimeline', 'enablePageMeta', 'components'];
1309
+ config = this.hooks.modifyConfig.call(config, componentName);
1310
+ const unofficialConfigs = ['enableShareAppMessage', 'enableShareTimeline', 'enablePageMeta', 'components', 'forceCustomWrapper'];
2059
1311
  unofficialConfigs.forEach(item => {
2060
1312
  delete config[item];
2061
1313
  });
@@ -2063,21 +1315,6 @@ class TaroMiniPlugin {
2063
1315
  const fileConfigStr = JSON.stringify(config);
2064
1316
  compilation.assets[fileConfigName] = new RawSource(fileConfigStr);
2065
1317
  }
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
- }
2081
1318
  generateTemplateFile(compilation, compiler, filePath, templateFn, ...options) {
2082
1319
  var _a;
2083
1320
  const { RawSource } = compiler.webpack.sources;
@@ -2216,10 +1453,13 @@ registerRecursiveComponent(${args})
2216
1453
  });
2217
1454
  });
2218
1455
  }
2219
- // 判断是否需要处理样式:有 common chunks 或者有 app.wxss
2220
- const hasMainPackageRoot = this.hasSubPackageIndieMainPackageRoot() && newBlended;
1456
+ // 判断是否需要处理样式:有 common chunks 或者有 app.wxss(可被扩展插件修改)
2221
1457
  const hasAppStyle = !!assets[appStyle];
2222
- const shouldProcessStyles = commons.size() > 0 || (hasMainPackageRoot && hasAppStyle);
1458
+ let shouldProcessStyles = commons.size() > 0;
1459
+ if (!hasAppStyle) {
1460
+ shouldProcessStyles = false;
1461
+ }
1462
+ shouldProcessStyles = this.hooks.modifyShouldProcessStyles.call(shouldProcessStyles);
2223
1463
  if (shouldProcessStyles) {
2224
1464
  const APP_STYLE_NAME = 'app-origin' + styleExt;
2225
1465
  assets[APP_STYLE_NAME] = new ConcatSource(originSource);
@@ -2236,7 +1476,6 @@ registerRecursiveComponent(${args})
2236
1476
  if (page.isNative)
2237
1477
  return;
2238
1478
  const pageStyle = `${page.name}${styleExt}`;
2239
- const indieMatch = this.getSubPackageIndieMatch(page.name);
2240
1479
  if (this.nativeComponents.has(page.name)) {
2241
1480
  // 本地化组件如果没有wxss则直接写入一个空的
2242
1481
  if (!(pageStyle in assets)) {
@@ -2244,17 +1483,18 @@ registerRecursiveComponent(${args})
2244
1483
  }
2245
1484
  const source = new ConcatSource('');
2246
1485
  const originSource = assets[pageStyle];
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" 继承入口组件的样式
1486
+ const styleImportContext = this.hooks.modifyStyleImport.call({
1487
+ importStatement: '',
1488
+ shouldSkip: false,
1489
+ isMainPackageRoot: false,
1490
+ }, page);
1491
+ if (styleImportContext.shouldSkip) {
1492
+ // no-op
1493
+ }
1494
+ else if (styleImportContext.importStatement) {
1495
+ source.add(styleImportContext.importStatement);
2255
1496
  }
2256
1497
  else {
2257
- // 非 subPackageIndie 分包:引用根目录的公共样式
2258
1498
  componentCommons.forEach(item => {
2259
1499
  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
1500
  });
@@ -2264,15 +1504,18 @@ registerRecursiveComponent(${args})
2264
1504
  }
2265
1505
  else {
2266
1506
  // 普通页面(非本地化组件)
2267
- if (indieMatch === null || indieMatch === void 0 ? void 0 : indieMatch.isMainPackageRoot) {
2268
- // mainPackageRoot 下的页面:只需 @import './app.wxss'(它已包含 common.wxss 等)
1507
+ const styleImportContext = this.hooks.modifyStyleImport.call({
1508
+ importStatement: '',
1509
+ shouldSkip: false,
1510
+ isMainPackageRoot: false,
1511
+ }, page);
1512
+ if (styleImportContext.importStatement) {
2269
1513
  const source = new ConcatSource('');
2270
1514
  if (pageStyle in assets) {
2271
1515
  source.add(assets[pageStyle]);
2272
1516
  }
2273
- // 创建或更新样式文件,添加 app.wxss 引用
2274
1517
  const importSource = new ConcatSource('');
2275
- importSource.add(`@import ${JSON.stringify((0, loader_utils_1.urlToRequest)('./app' + styleExt))};\n`);
1518
+ importSource.add(styleImportContext.importStatement);
2276
1519
  importSource.add(source);
2277
1520
  assets[pageStyle] = importSource;
2278
1521
  }