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

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,26 @@ 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");
22
47
  const webpack_1 = require("../utils/webpack");
48
+ const SubPackageIndiePlugin_1 = __importStar(require("./SubPackageIndiePlugin"));
23
49
  const TaroLoadChunksPlugin_1 = __importDefault(require("./TaroLoadChunksPlugin"));
24
50
  const TaroNormalModulesPlugin_1 = __importDefault(require("./TaroNormalModulesPlugin"));
25
51
  const TaroSingleEntryPlugin_1 = __importDefault(require("./TaroSingleEntryPlugin"));
26
- const baseCompName = 'comp';
27
- const customWrapperName = 'custom-wrapper';
28
- const subPackageIndieCustomWrapperRootsKey = '__taroSubPackageIndieCustomWrapperRoots';
29
- const recursiveComponentName = 'recursive-component';
52
+ exports.baseCompName = 'comp';
53
+ exports.customWrapperName = 'custom-wrapper';
30
54
  const PLUGIN_NAME = 'TaroMiniPlugin';
31
55
  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';
56
+ exports.STYLE_ISOLATION_APPLY_SHARED = 'apply-shared';
57
+ exports.STYLE_ISOLATION_SHARED = 'shared';
35
58
  function isLoaderExist(loaders, loaderName) {
36
59
  return loaders.some(item => item.loader === loaderName);
37
60
  }
@@ -51,7 +74,7 @@ class TaroMiniPlugin {
51
74
  this.dependencies = new Map();
52
75
  this.pageLoaderName = '@tarojs/taro-loader/lib/page';
53
76
  this.independentPackages = new Map();
54
- this.moduleRequestMap = new Map();
77
+ this.subPackageIndiePlugin = null;
55
78
  const { combination } = options;
56
79
  const miniBuildConfig = combination.config;
57
80
  const { template, baseLevel = 16, experimental } = miniBuildConfig;
@@ -75,6 +98,22 @@ class TaroMiniPlugin {
75
98
  hot: options.hot,
76
99
  loaderMeta: options.loaderMeta || {},
77
100
  };
101
+ // 初始化扩展钩子
102
+ this.hooks = {
103
+ modifyEntries: new tapable_1.SyncWaterfallHook(['entries']),
104
+ modifyChunkRequire: new tapable_1.SyncWaterfallHook(['result', 'chunkId', 'miniType']),
105
+ afterResolveModule: new tapable_1.SyncHook(['resolveData']),
106
+ compileExtraEntries: new tapable_1.SyncHook(['compiler', 'compilation', 'promises']),
107
+ modifySkipRootTemplates: new tapable_1.SyncWaterfallHook(['skip']),
108
+ generateExtraFiles: new tapable_1.SyncWaterfallHook(['customWrapperRoots', 'compilation', 'compiler']),
109
+ modifyPageConfig: new tapable_1.SyncWaterfallHook(['context', 'page', 'customWrapperRoots']),
110
+ modifyComponentConfig: new tapable_1.SyncHook(['context', 'customWrapperRoots']),
111
+ afterGenerateFiles: new tapable_1.SyncHook(['compilation', 'compiler']),
112
+ optimizeAssets: new tapable_1.SyncHook(['compilation']),
113
+ modifyConfig: new tapable_1.SyncWaterfallHook(['config', 'componentName']),
114
+ modifyStyleImport: new tapable_1.SyncWaterfallHook(['context', 'page']),
115
+ modifyShouldProcessStyles: new tapable_1.SyncWaterfallHook(['shouldProcess']),
116
+ };
78
117
  if (template.isSupportRecursive === false && baseLevel > 0) {
79
118
  template.baseLevel = baseLevel;
80
119
  }
@@ -105,6 +144,10 @@ class TaroMiniPlugin {
105
144
  apply(compiler) {
106
145
  this.context = compiler.context;
107
146
  this.appEntry = this.getAppEntry(compiler);
147
+ if (this.options.newBlended) {
148
+ this.subPackageIndiePlugin = new SubPackageIndiePlugin_1.default(this);
149
+ this.subPackageIndiePlugin.apply();
150
+ }
108
151
  const { commonChunks, combination, framework, isBuildPlugin, newBlended, } = this.options;
109
152
  const { addChunkPages, onCompilerMake, modifyBuildAssets, onParseCreateElement, } = combination.config;
110
153
  /** build mode */
@@ -141,7 +184,7 @@ class TaroMiniPlugin {
141
184
  const dependencies = this.dependencies;
142
185
  const promises = [];
143
186
  this.compileIndependentPages(compiler, compilation, dependencies, promises);
144
- this.compileSubPackageIndieStandaloneEntries(compiler, compilation, promises);
187
+ this.hooks.compileExtraEntries.call(compiler, compilation, promises);
145
188
  dependencies.forEach(dep => {
146
189
  promises.push(new Promise((resolve, reject) => {
147
190
  compilation.addEntry(this.options.sourceDir, dep, Object.assign({ name: dep.name }, dep.options), err => err ? reject(err) : resolve(null));
@@ -156,40 +199,7 @@ class TaroMiniPlugin {
156
199
  compilation.dependencyFactories.set(TaroSingleEntryDependency_1.default, normalModuleFactory);
157
200
  if (this.options.newBlended) {
158
201
  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
- });
202
+ this.hooks.afterResolveModule.call(resolveData);
193
203
  });
194
204
  }
195
205
  /**
@@ -270,7 +280,7 @@ class TaroMiniPlugin {
270
280
  name: PLUGIN_NAME,
271
281
  stage: PROCESS_ASSETS_STAGE_ADDITIONAL
272
282
  }, this.tryAsync(() => __awaiter(this, void 0, void 0, function* () {
273
- if (compilation.__tag === SUBPACKAGE_STANDALONE_CHILD_TAG)
283
+ if (compilation.__tag === SubPackageIndiePlugin_1.SUBPACKAGE_STANDALONE_CHILD_TAG)
274
284
  return;
275
285
  // 如果是子编译器,证明是编译独立分包,进行单独的处理
276
286
  if (compilation.__tag === CHILD_COMPILER_TAG) {
@@ -286,7 +296,7 @@ class TaroMiniPlugin {
286
296
  // Stage 触发顺序:https://webpack.js.org/api/compilation-hooks/#list-of-asset-processing-stages
287
297
  stage: PROCESS_ASSETS_STAGE_OPTIMIZE
288
298
  }, this.tryAsync(() => __awaiter(this, void 0, void 0, function* () {
289
- if (compilation.__tag === SUBPACKAGE_STANDALONE_CHILD_TAG)
299
+ if (compilation.__tag === SubPackageIndiePlugin_1.SUBPACKAGE_STANDALONE_CHILD_TAG)
290
300
  return;
291
301
  yield this.optimizeMiniFiles(compilation, compiler);
292
302
  })));
@@ -295,7 +305,7 @@ class TaroMiniPlugin {
295
305
  // 该 stage 是最后执行的,确保 taro 暴露给用户的钩子 modifyBuildAssets 在内部处理完 assets 之后再调用
296
306
  stage: PROCESS_ASSETS_STAGE_REPORT
297
307
  }, this.tryAsync(() => __awaiter(this, void 0, void 0, function* () {
298
- if (compilation.__tag === SUBPACKAGE_STANDALONE_CHILD_TAG)
308
+ if (compilation.__tag === SubPackageIndiePlugin_1.SUBPACKAGE_STANDALONE_CHILD_TAG)
299
309
  return;
300
310
  if (typeof modifyBuildAssets === 'function') {
301
311
  yield modifyBuildAssets(compilation.assets, this);
@@ -341,15 +351,13 @@ class TaroMiniPlugin {
341
351
  let source;
342
352
  const id = (0, webpack_1.getChunkIdOrName)(chunk);
343
353
  const { miniType } = entryModule;
354
+ const modifyResult = this.hooks.modifyChunkRequire.call({ source: modules, handled: false }, id, miniType);
355
+ if (modifyResult === null || modifyResult === void 0 ? void 0 : modifyResult.handled) {
356
+ return modifyResult.source;
357
+ }
344
358
  const entryChunk = [{ name: 'app' }];
345
359
  // 所有模块都依赖app.js,确保@tarojs\plugin-platform-xxx\dist\runtime.js先于@tarojs/runtime执行,避免Taro API未被初始化
346
360
  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
361
  fileChunks.forEach((v, k) => {
354
362
  if (k === id) {
355
363
  source = (0, webpack_1.addRequireToSource)(id, modules, v);
@@ -359,12 +367,6 @@ class TaroMiniPlugin {
359
367
  return source || modules;
360
368
  }
361
369
  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
370
  return (0, webpack_1.addRequireToSource)(id, modules, entryChunk);
369
371
  }
370
372
  }
@@ -541,12 +543,12 @@ class TaroMiniPlugin {
541
543
  }
542
544
  if (!this.options.template.isSupportRecursive) {
543
545
  pluginJSON.publicComponents = Object.assign({}, publicComponents, {
544
- [baseCompName]: baseCompName
546
+ [exports.baseCompName]: exports.baseCompName
545
547
  });
546
548
  }
547
549
  if (isUsingCustomWrapper) {
548
550
  pluginJSON.publicComponents = Object.assign({}, publicComponents, {
549
- [customWrapperName]: customWrapperName
551
+ [exports.customWrapperName]: exports.customWrapperName
550
552
  });
551
553
  }
552
554
  }
@@ -634,113 +636,6 @@ class TaroMiniPlugin {
634
636
  this.nativeComponents.set(item, componentObj);
635
637
  });
636
638
  }
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
639
  /**
745
640
  * 读取页面及其依赖的组件的配置
746
641
  */
@@ -803,14 +698,16 @@ class TaroMiniPlugin {
803
698
  * 在 this.dependencies 中新增或修改 app、模板组件、页面、组件等资源模块
804
699
  */
805
700
  addEntries() {
806
- const { template, newBlended } = this.options;
701
+ const { template } = this.options;
807
702
  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) {
703
+ const entryFlags = this.hooks.modifyEntries.call({
704
+ skipRootComp: false,
705
+ skipRootWrapper: false,
706
+ });
707
+ if (!template.isSupportRecursive && !entryFlags.skipRootComp) {
811
708
  this.addEntry(node_path_1.default.resolve(__dirname, '..', 'template/comp'), 'comp', helper_1.META_TYPE.STATIC);
812
709
  }
813
- if (!skipRootEntries) {
710
+ if (!entryFlags.skipRootWrapper) {
814
711
  this.addEntry(node_path_1.default.resolve(__dirname, '..', 'template/custom-wrapper'), 'custom-wrapper', helper_1.META_TYPE.STATIC);
815
712
  }
816
713
  // subPackageIndie 下的 comp/custom-wrapper 统一走独立子编译器,避免被主编译的公共 chunk 共享
@@ -1079,45 +976,6 @@ class TaroMiniPlugin {
1079
976
  });
1080
977
  }
1081
978
  }
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
979
  /**
1122
980
  * 搜集 tabbar icon 图标路径
1123
981
  * 收集自定义 tabbar 组件
@@ -1186,546 +1044,6 @@ class TaroMiniPlugin {
1186
1044
  return;
1187
1045
  thirdPartyComponents.set(componentName, new Set(attrs));
1188
1046
  }
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
1047
  /** 生成小程序独立分包的相关文件 */
1730
1048
  generateIndependentMiniFiles(compilation, compiler) {
1731
1049
  return __awaiter(this, void 0, void 0, function* () {
@@ -1744,25 +1062,25 @@ class TaroMiniPlugin {
1744
1062
  // 如微信、QQ 不支持递归模版的小程序,需要使用自定义组件协助递归
1745
1063
  const compConfig = {
1746
1064
  component: true,
1747
- styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1065
+ styleIsolation: exports.STYLE_ISOLATION_APPLY_SHARED,
1748
1066
  usingComponents: {
1749
- [baseCompName]: `./${baseCompName}`
1067
+ [exports.baseCompName]: `./${exports.baseCompName}`
1750
1068
  }
1751
1069
  };
1752
1070
  if (isUsingCustomWrapper) {
1753
- compConfig.usingComponents[customWrapperName] = `./${customWrapperName}`;
1071
+ compConfig.usingComponents[exports.customWrapperName] = `./${exports.customWrapperName}`;
1754
1072
  }
1755
- this.generateConfigFile(compilation, compiler, `${name}/${baseCompName}`, compConfig);
1756
- this.generateTemplateFile(compilation, compiler, `${name}/${baseCompName}`, template.buildBaseComponentTemplate, this.options.fileType.templ);
1073
+ this.generateConfigFile(compilation, compiler, `${name}/${exports.baseCompName}`, compConfig);
1074
+ this.generateTemplateFile(compilation, compiler, `${name}/${exports.baseCompName}`, template.buildBaseComponentTemplate, this.options.fileType.templ);
1757
1075
  }
1758
- this.generateConfigFile(compilation, compiler, `${name}/${customWrapperName}`, {
1076
+ this.generateConfigFile(compilation, compiler, `${name}/${exports.customWrapperName}`, {
1759
1077
  component: true,
1760
- styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1078
+ styleIsolation: exports.STYLE_ISOLATION_APPLY_SHARED,
1761
1079
  usingComponents: {
1762
- [customWrapperName]: `./${customWrapperName}`
1080
+ [exports.customWrapperName]: `./${exports.customWrapperName}`
1763
1081
  }
1764
1082
  });
1765
- this.generateTemplateFile(compilation, compiler, `${name}/${customWrapperName}`, template.buildCustomComponentTemplate, this.options.fileType.templ);
1083
+ this.generateTemplateFile(compilation, compiler, `${name}/${exports.customWrapperName}`, template.buildCustomComponentTemplate, this.options.fileType.templ);
1766
1084
  this.generateXSFile(compilation, compiler, `${name}/utils`);
1767
1085
  });
1768
1086
  this.pages.forEach(page => {
@@ -1785,14 +1103,14 @@ class TaroMiniPlugin {
1785
1103
  this.generateTemplateFile(compilation, compiler, page.path, template.buildPageTemplate, importBaseTemplatePath, config);
1786
1104
  }
1787
1105
  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, ''))));
1106
+ const importBaseCompPath = (0, helper_1.promoteRelativePath)(node_path_1.default.relative(page.path, node_path_1.default.join(sourceDir, independentName, this.getTargetFilePath(exports.baseCompName, ''))));
1107
+ 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
1108
  config.content.usingComponents = Object.assign({}, config.content.usingComponents);
1791
1109
  if (isUsingCustomWrapper) {
1792
- config.content.usingComponents[customWrapperName] = importCustomWrapperPath;
1110
+ config.content.usingComponents[exports.customWrapperName] = importCustomWrapperPath;
1793
1111
  }
1794
1112
  if (!template.isSupportRecursive && !page.isNative) {
1795
- config.content.usingComponents[baseCompName] = importBaseCompPath;
1113
+ config.content.usingComponents[exports.baseCompName] = importBaseCompPath;
1796
1114
  }
1797
1115
  this.generateConfigFile(compilation, compiler, page.path, config.content);
1798
1116
  }
@@ -1808,7 +1126,7 @@ class TaroMiniPlugin {
1808
1126
  const baseTemplateName = 'base';
1809
1127
  const isUsingCustomWrapper = component_1.componentConfig.thirdPartyComponents.has('custom-wrapper');
1810
1128
  let subPackageIndieCustomWrapperRoots = new Set();
1811
- compilation[subPackageIndieCustomWrapperRootsKey] = subPackageIndieCustomWrapperRoots;
1129
+ compilation[SubPackageIndiePlugin_1.subPackageIndieCustomWrapperRootsKey] = subPackageIndieCustomWrapperRoots;
1812
1130
  /**
1813
1131
  * 与原生小程序混写时解析模板与样式
1814
1132
  */
@@ -1828,38 +1146,38 @@ class TaroMiniPlugin {
1828
1146
  const appConfigName = node_path_1.default.basename(appConfigPath).replace(node_path_1.default.extname(appConfigPath), '');
1829
1147
  this.generateConfigFile(compilation, compiler, this.appEntry, this.filesConfig[appConfigName].content);
1830
1148
  }
1831
- // 当配置了 mainPackageRoot 时,跳过根目录模板文件的生成
1832
- const skipRootTemplates = this.hasSubPackageIndieMainPackageRoot() && this.options.newBlended;
1149
+ let skipRootTemplates = false;
1150
+ skipRootTemplates = this.hooks.modifySkipRootTemplates.call(skipRootTemplates);
1833
1151
  if (!template.isSupportRecursive && !skipRootTemplates) {
1834
1152
  // 如微信、QQ 不支持递归模版的小程序,需要使用自定义组件协助递归
1835
- this.generateTemplateFile(compilation, compiler, baseCompName, template.buildBaseComponentTemplate, this.options.fileType.templ);
1153
+ this.generateTemplateFile(compilation, compiler, exports.baseCompName, template.buildBaseComponentTemplate, this.options.fileType.templ);
1836
1154
  const baseCompConfig = {
1837
1155
  component: true,
1838
- styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1156
+ styleIsolation: exports.STYLE_ISOLATION_APPLY_SHARED,
1839
1157
  usingComponents: {
1840
- [baseCompName]: `./${baseCompName}`
1158
+ [exports.baseCompName]: `./${exports.baseCompName}`
1841
1159
  }
1842
1160
  };
1843
1161
  if (isUsingCustomWrapper) {
1844
- baseCompConfig.usingComponents[customWrapperName] = `./${customWrapperName}`;
1845
- this.generateConfigFile(compilation, compiler, customWrapperName, {
1162
+ baseCompConfig.usingComponents[exports.customWrapperName] = `./${exports.customWrapperName}`;
1163
+ this.generateConfigFile(compilation, compiler, exports.customWrapperName, {
1846
1164
  component: true,
1847
- styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1165
+ styleIsolation: exports.STYLE_ISOLATION_APPLY_SHARED,
1848
1166
  usingComponents: {
1849
- [baseCompName]: `./${baseCompName}`,
1850
- [customWrapperName]: `./${customWrapperName}`
1167
+ [exports.baseCompName]: `./${exports.baseCompName}`,
1168
+ [exports.customWrapperName]: `./${exports.customWrapperName}`
1851
1169
  }
1852
1170
  });
1853
1171
  }
1854
- this.generateConfigFile(compilation, compiler, baseCompName, baseCompConfig);
1172
+ this.generateConfigFile(compilation, compiler, exports.baseCompName, baseCompConfig);
1855
1173
  }
1856
1174
  else if (!skipRootTemplates) {
1857
1175
  if (isUsingCustomWrapper) {
1858
- this.generateConfigFile(compilation, compiler, customWrapperName, {
1176
+ this.generateConfigFile(compilation, compiler, exports.customWrapperName, {
1859
1177
  component: true,
1860
- styleIsolation: STYLE_ISOLATION_APPLY_SHARED,
1178
+ styleIsolation: exports.STYLE_ISOLATION_APPLY_SHARED,
1861
1179
  usingComponents: {
1862
- [customWrapperName]: `./${customWrapperName}`
1180
+ [exports.customWrapperName]: `./${exports.customWrapperName}`
1863
1181
  }
1864
1182
  });
1865
1183
  }
@@ -1867,34 +1185,16 @@ class TaroMiniPlugin {
1867
1185
  // ★ 当配置了 mainPackageRoot 时,跳过根目录 base.wxml 和 utils.wxs 的生成
1868
1186
  if (!skipRootTemplates) {
1869
1187
  this.generateTemplateFile(compilation, compiler, baseTemplateName, template.buildTemplate, component_1.componentConfig);
1870
- isUsingCustomWrapper && this.generateTemplateFile(compilation, compiler, customWrapperName, template.buildCustomComponentTemplate, this.options.fileType.templ);
1188
+ isUsingCustomWrapper && this.generateTemplateFile(compilation, compiler, exports.customWrapperName, template.buildCustomComponentTemplate, this.options.fileType.templ);
1871
1189
  this.generateXSFile(compilation, compiler, 'utils');
1872
1190
  }
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
- }
1191
+ subPackageIndieCustomWrapperRoots = this.hooks.generateExtraFiles.call(subPackageIndieCustomWrapperRoots, compilation, compiler);
1192
+ compilation[SubPackageIndiePlugin_1.subPackageIndieCustomWrapperRootsKey] = subPackageIndieCustomWrapperRoots;
1880
1193
  this.components.forEach(component => {
1881
1194
  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
1195
  const config = this.filesConfig[this.getConfigFilePath(component.name)];
1883
1196
  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
- }
1197
+ this.hooks.modifyComponentConfig.call({ config, component }, subPackageIndieCustomWrapperRoots);
1898
1198
  this.generateConfigFile(compilation, compiler, component.path, config.content);
1899
1199
  }
1900
1200
  if (!component.isNative) {
@@ -1902,61 +1202,46 @@ class TaroMiniPlugin {
1902
1202
  }
1903
1203
  });
1904
1204
  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
- }
1205
+ 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
1206
  const config = this.filesConfig[this.getConfigFilePath(page.name)];
1917
1207
  // pages 里面会混合独立分包的,在这里需要过滤一下,避免重复生成 assets
1918
1208
  const isIndependent = !!this.getIndependentPackage(page.path);
1919
1209
  if (isIndependent)
1920
1210
  return;
1921
1211
  // 生成页面模板需要在生成页面配置之前,因为会依赖到页面配置的部分内容
1212
+ 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, ''))));
1213
+ 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, ''))));
1214
+ let isPageRecursiveDisabled = false;
1215
+ let shouldUseCustomWrapper = isUsingCustomWrapper;
1216
+ const pageConfigContext = this.hooks.modifyPageConfig.call({
1217
+ importBaseTemplatePath,
1218
+ importBaseCompPath,
1219
+ importCustomWrapperPath,
1220
+ shouldUseCustomWrapper,
1221
+ isPageRecursiveDisabled,
1222
+ }, page, subPackageIndieCustomWrapperRoots);
1223
+ importBaseTemplatePath = pageConfigContext.importBaseTemplatePath;
1224
+ importBaseCompPath = pageConfigContext.importBaseCompPath;
1225
+ importCustomWrapperPath = pageConfigContext.importCustomWrapperPath;
1226
+ shouldUseCustomWrapper = pageConfigContext.shouldUseCustomWrapper;
1227
+ isPageRecursiveDisabled = pageConfigContext.isPageRecursiveDisabled;
1922
1228
  if (!page.isNative) {
1923
1229
  this.generateTemplateFile(compilation, compiler, page.path, template.buildPageTemplate, importBaseTemplatePath, config);
1924
1230
  }
1925
1231
  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
1232
  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
1233
  if (shouldUseCustomWrapper) {
1946
- config.content.usingComponents[customWrapperName] = importCustomWrapperPath;
1234
+ config.content.usingComponents[exports.customWrapperName] = importCustomWrapperPath;
1947
1235
  }
1948
1236
  if (!template.isSupportRecursive && !page.isNative && !isPageRecursiveDisabled) {
1949
- config.content.usingComponents[baseCompName] = importBaseCompPath;
1237
+ config.content.usingComponents[exports.baseCompName] = importBaseCompPath;
1950
1238
  }
1951
1239
  this.generateConfigFile(compilation, compiler, page.path, config.content);
1952
1240
  }
1953
1241
  });
1954
1242
  this.generateTabBarFiles(compilation, compiler);
1955
1243
  this.injectCommonStyles(compilation, compiler);
1956
- // ★ 为 mainPackageRoot 生成 runtime chunks(必须在 injectCommonStyles 之后,因为需要复制处理后的 app.wxss)
1957
- if (this.hasSubPackageIndieMainPackageRoot() && this.options.newBlended) {
1958
- this.generateMainPackageRuntimeFiles(compilation, compiler);
1959
- }
1244
+ this.hooks.afterGenerateFiles.call(compilation, compiler);
1960
1245
  if (this.themeLocation) {
1961
1246
  this.generateDarkModeFile(compilation, compiler);
1962
1247
  }
@@ -1973,11 +1258,6 @@ class TaroMiniPlugin {
1973
1258
  optimizeMiniFiles(compilation, _compiler) {
1974
1259
  return __awaiter(this, void 0, void 0, function* () {
1975
1260
  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
1261
  /**
1982
1262
  * 与原生小程序混写时解析模板与样式
1983
1263
  */
@@ -1994,67 +1274,14 @@ class TaroMiniPlugin {
1994
1274
  delete compilation.assets[assetPath];
1995
1275
  }
1996
1276
  });
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
- }
1277
+ this.hooks.optimizeAssets.call(compilation);
2043
1278
  });
2044
1279
  }
2045
1280
  generateConfigFile(compilation, compiler, filePath, config) {
2046
1281
  const { RawSource } = compiler.webpack.sources;
2047
1282
  const fileConfigName = this.getConfigPath(this.getComponentName(filePath));
2048
- // ★ 为子分包独立模板的组件注入额外配置
2049
1283
  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
- }
1284
+ config = this.hooks.modifyConfig.call(config, componentName);
2058
1285
  const unofficialConfigs = ['enableShareAppMessage', 'enableShareTimeline', 'enablePageMeta', 'components'];
2059
1286
  unofficialConfigs.forEach(item => {
2060
1287
  delete config[item];
@@ -2216,10 +1443,13 @@ registerRecursiveComponent(${args})
2216
1443
  });
2217
1444
  });
2218
1445
  }
2219
- // 判断是否需要处理样式:有 common chunks 或者有 app.wxss
2220
- const hasMainPackageRoot = this.hasSubPackageIndieMainPackageRoot() && newBlended;
1446
+ // 判断是否需要处理样式:有 common chunks 或者有 app.wxss(可被扩展插件修改)
2221
1447
  const hasAppStyle = !!assets[appStyle];
2222
- const shouldProcessStyles = commons.size() > 0 || (hasMainPackageRoot && hasAppStyle);
1448
+ let shouldProcessStyles = commons.size() > 0;
1449
+ if (!hasAppStyle) {
1450
+ shouldProcessStyles = false;
1451
+ }
1452
+ shouldProcessStyles = this.hooks.modifyShouldProcessStyles.call(shouldProcessStyles);
2223
1453
  if (shouldProcessStyles) {
2224
1454
  const APP_STYLE_NAME = 'app-origin' + styleExt;
2225
1455
  assets[APP_STYLE_NAME] = new ConcatSource(originSource);
@@ -2236,7 +1466,6 @@ registerRecursiveComponent(${args})
2236
1466
  if (page.isNative)
2237
1467
  return;
2238
1468
  const pageStyle = `${page.name}${styleExt}`;
2239
- const indieMatch = this.getSubPackageIndieMatch(page.name);
2240
1469
  if (this.nativeComponents.has(page.name)) {
2241
1470
  // 本地化组件如果没有wxss则直接写入一个空的
2242
1471
  if (!(pageStyle in assets)) {
@@ -2244,17 +1473,18 @@ registerRecursiveComponent(${args})
2244
1473
  }
2245
1474
  const source = new ConcatSource('');
2246
1475
  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" 继承入口组件的样式
1476
+ const styleImportContext = this.hooks.modifyStyleImport.call({
1477
+ importStatement: '',
1478
+ shouldSkip: false,
1479
+ isMainPackageRoot: false,
1480
+ }, page);
1481
+ if (styleImportContext.shouldSkip) {
1482
+ // no-op
1483
+ }
1484
+ else if (styleImportContext.importStatement) {
1485
+ source.add(styleImportContext.importStatement);
2255
1486
  }
2256
1487
  else {
2257
- // 非 subPackageIndie 分包:引用根目录的公共样式
2258
1488
  componentCommons.forEach(item => {
2259
1489
  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
1490
  });
@@ -2264,15 +1494,18 @@ registerRecursiveComponent(${args})
2264
1494
  }
2265
1495
  else {
2266
1496
  // 普通页面(非本地化组件)
2267
- if (indieMatch === null || indieMatch === void 0 ? void 0 : indieMatch.isMainPackageRoot) {
2268
- // mainPackageRoot 下的页面:只需 @import './app.wxss'(它已包含 common.wxss 等)
1497
+ const styleImportContext = this.hooks.modifyStyleImport.call({
1498
+ importStatement: '',
1499
+ shouldSkip: false,
1500
+ isMainPackageRoot: false,
1501
+ }, page);
1502
+ if (styleImportContext.importStatement) {
2269
1503
  const source = new ConcatSource('');
2270
1504
  if (pageStyle in assets) {
2271
1505
  source.add(assets[pageStyle]);
2272
1506
  }
2273
- // 创建或更新样式文件,添加 app.wxss 引用
2274
1507
  const importSource = new ConcatSource('');
2275
- importSource.add(`@import ${JSON.stringify((0, loader_utils_1.urlToRequest)('./app' + styleExt))};\n`);
1508
+ importSource.add(styleImportContext.importStatement);
2276
1509
  importSource.add(source);
2277
1510
  assets[pageStyle] = importSource;
2278
1511
  }