@umijs/plugins 4.0.0-canary.20240624.1 → 4.0.0-canary.20240702.1

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.
package/dist/antd.js CHANGED
@@ -269,6 +269,8 @@ var antd_default = (api) => {
269
269
  const enableV5ThemeAlgorithm = isV5 && (userInputCompact || userInputDark) ? { compact: userInputCompact, dark: userInputDark } : false;
270
270
  const hasConfigProvider = configProvider || enableV5ThemeAlgorithm;
271
271
  const antdConfigSetter = isV5 && hasConfigProvider;
272
+ const isModelPluginEnabled = api.isPluginEnable("model");
273
+ const modelPluginCompat = isModelPluginEnabled && antdConfigSetter;
272
274
  api.writeTmpFile({
273
275
  path: `runtime.tsx`,
274
276
  context: {
@@ -278,6 +280,7 @@ var antd_default = (api) => {
278
280
  // 是否启用了 v5 的 theme algorithm
279
281
  enableV5ThemeAlgorithm,
280
282
  antdConfigSetter,
283
+ modelPluginCompat,
281
284
  lodashPath,
282
285
  /**
283
286
  * 是否重构了全局静态配置。 重构后需要在运行时将全局静态配置传入到 ConfigProvider 中。
@@ -65,7 +65,7 @@ export default function InitialStateProvider(props: any) {
65
65
  appLoaded.current = true;
66
66
  }
67
67
  }, [loading]);
68
- if (loading && !appLoaded.current) {
68
+ if (loading && !appLoaded.current && typeof window !== 'undefined') {
69
69
  return <Loading />;
70
70
  }
71
71
  return props.children;
package/dist/mf.js CHANGED
@@ -1,8 +1,6 @@
1
- var __create = Object.create;
2
1
  var __defProp = Object.defineProperty;
3
2
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
5
  var __export = (target, all) => {
8
6
  for (var name in all)
@@ -16,14 +14,6 @@ var __copyProps = (to, from, except, desc) => {
16
14
  }
17
15
  return to;
18
16
  };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
17
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
18
 
29
19
  // src/mf.ts
@@ -37,23 +27,16 @@ var import_fs = require("fs");
37
27
  var import_path = require("path");
38
28
  var import_plugin_utils = require("umi/plugin-utils");
39
29
  var import_constants = require("./constants");
40
- var import_mf_v2 = __toESM(require("./mf-v2"));
41
30
  var import_mfUtils = require("./utils/mfUtils");
42
31
  var { isEmpty } = import_plugin_utils.lodash;
43
32
  var mfSetupPathFileName = "_mf_setup-public-path.js";
44
33
  var mfAsyncEntryFileName = "asyncEntry.ts";
45
34
  var MF_TEMPLATES_DIR = (0, import_path.join)(import_constants.TEMPLATES_DIR, "mf");
46
35
  function mf(api) {
47
- var _a, _b;
48
36
  api.describe({
49
37
  key: "mf",
50
38
  config: {
51
39
  schema({ zod }) {
52
- var _a2;
53
- const useVersion = (_a2 = api.userConfig.mf) == null ? void 0 : _a2.version;
54
- if (useVersion === import_mf_v2.EVersion.v2) {
55
- return (0, import_mf_v2.configSchema)(zod);
56
- }
57
40
  return zod.object({
58
41
  name: zod.string(),
59
42
  remotes: zod.array(
@@ -68,18 +51,12 @@ function mf(api) {
68
51
  ),
69
52
  shared: zod.record(zod.any()),
70
53
  library: zod.record(zod.any()),
71
- remoteHash: zod.boolean(),
72
- version: zod.enum([import_mf_v2.EVersion.v1, import_mf_v2.EVersion.v2])
54
+ remoteHash: zod.boolean()
73
55
  }).partial();
74
56
  }
75
57
  },
76
58
  enableBy: api.EnableBy.config
77
59
  });
78
- const useV2 = ((_a = api.userConfig.mf) == null ? void 0 : _a.version) === import_mf_v2.EVersion.v2 || ((_b = api.config.mf) == null ? void 0 : _b.version) === import_mf_v2.EVersion.v2;
79
- if (useV2) {
80
- (0, import_mf_v2.default)(api, { standalone: false });
81
- return;
82
- }
83
60
  api.modifyWebpackConfig(async (config, { webpack }) => {
84
61
  const exposes = await constructExposes();
85
62
  const remotes = formatRemotes();
@@ -272,7 +249,7 @@ function mf(api) {
272
249
  `module federation name is not defined , "unNamedMF" will be used`
273
250
  );
274
251
  }
275
- if (!(0, import_mf_v2.isValidIdentifyName)(name)) {
252
+ if (!isValidIdentifyName(name)) {
276
253
  throw new Error(
277
254
  `module federation name '${name}' is not valid javascript identifier.`
278
255
  );
@@ -308,4 +285,74 @@ function mf(api) {
308
285
  function addMFEntry(config, mfName2, path) {
309
286
  config.entry[mfName2] = path;
310
287
  }
288
+ function isValidIdentifyName(name) {
289
+ const reservedKeywords = [
290
+ "abstract",
291
+ "await",
292
+ "boolean",
293
+ "break",
294
+ "byte",
295
+ "case",
296
+ "catch",
297
+ "char",
298
+ "class",
299
+ "const",
300
+ "continue",
301
+ "debugger",
302
+ "default",
303
+ "delete",
304
+ "do",
305
+ "double",
306
+ "else",
307
+ "enum",
308
+ "export",
309
+ "extends",
310
+ "false",
311
+ "final",
312
+ "finally",
313
+ "float",
314
+ "for",
315
+ "function",
316
+ "goto",
317
+ "if",
318
+ "implements",
319
+ "import",
320
+ "in",
321
+ "instanceof",
322
+ "int",
323
+ "interface",
324
+ "let",
325
+ "long",
326
+ "native",
327
+ "new",
328
+ "null",
329
+ "package",
330
+ "private",
331
+ "protected",
332
+ "public",
333
+ "return",
334
+ "short",
335
+ "static",
336
+ "super",
337
+ "switch",
338
+ "synchronized",
339
+ "this",
340
+ "throw",
341
+ "transient",
342
+ "true",
343
+ "try",
344
+ "typeof",
345
+ "var",
346
+ "void",
347
+ "volatile",
348
+ "while",
349
+ "with",
350
+ "yield"
351
+ ];
352
+ const regexIdentifierName = /^(?:[$_\p{ID_Start}])(?:[$_\u200C\u200D\p{ID_Continue}])*$/u;
353
+ if (reservedKeywords.includes(name) || !regexIdentifierName.test(name)) {
354
+ return false;
355
+ }
356
+ return true;
357
+ }
311
358
  }
@@ -219,6 +219,16 @@ export { MicroAppWithMemoHistory } from './MicroAppWithMemoHistory';
219
219
  `
220
220
  });
221
221
  });
222
+ api.chainWebpack((config, { ssr }) => {
223
+ if (ssr) {
224
+ const originalExternals = config.get("externals");
225
+ config.externals({
226
+ ...originalExternals,
227
+ qiankun: "fs"
228
+ });
229
+ }
230
+ return config;
231
+ });
222
232
  };
223
233
  // Annotate the CommonJS export names for ESM import in node:
224
234
  0 && (module.exports = {
@@ -171,7 +171,10 @@ export interface IRuntimeConfig {
171
171
  `window.publicPath = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ || "${api.config.publicPath || "/"}";`
172
172
  ];
173
173
  });
174
- api.chainWebpack((config) => {
174
+ api.chainWebpack((config, { ssr }) => {
175
+ if (ssr) {
176
+ return;
177
+ }
175
178
  (0, import_assert.default)(api.pkg.name, "You should have name in package.json.");
176
179
  const {
177
180
  shouldNotAddLibraryChunkName = api.env === "production" || !Boolean(api.config.mfsu)
@@ -201,11 +204,14 @@ export interface IRuntimeConfig {
201
204
  });
202
205
  api.addEntryCode(() => [
203
206
  `
204
- export const bootstrap = qiankun_genBootstrap(render);
205
- export const mount = qiankun_genMount('${api.config.mountElementId}');
206
- export const unmount = qiankun_genUnmount('${api.config.mountElementId}');
207
- export const update = qiankun_genUpdate();
208
- if (!window.__POWERED_BY_QIANKUN__) {
207
+ const qiankun_noop = () => new Error('qiankun lifecycle is not available for server runtime!');
208
+ const isServer = typeof window === 'undefined';
209
+ export const bootstrap = isServer ? qiankun_noop: qiankun_genBootstrap(render);
210
+ export const mount = isServer ? qiankun_noop : qiankun_genMount('${api.config.mountElementId}');
211
+ export const unmount = isServer ? qiankun_noop : qiankun_genUnmount('${api.config.mountElementId}');
212
+ export const update = isServer ? qiankun_noop : qiankun_genUpdate();
213
+ // 增加 ssr 的判断
214
+ if (!isServer && !window.__POWERED_BY_QIANKUN__) {
209
215
  bootstrap().then(mount);
210
216
  }
211
217
  `
@@ -1,5 +1,7 @@
1
1
  import * as t from '@umijs/bundler-utils/compiled/babel/types';
2
+ import { type TransformResult } from '@umijs/bundler-utils/compiled/esbuild';
2
3
  import { IApi } from 'umi';
4
+ export declare function transformSync(content: any, opts: any): TransformResult<any>;
3
5
  interface IOpts {
4
6
  contentTest?: (content: string) => Boolean;
5
7
  astTest?: (opts: {
@@ -31,7 +31,8 @@ var modelUtils_exports = {};
31
31
  __export(modelUtils_exports, {
32
32
  Model: () => Model,
33
33
  ModelUtils: () => ModelUtils,
34
- getNamespace: () => getNamespace
34
+ getNamespace: () => getNamespace,
35
+ transformSync: () => transformSync
35
36
  });
36
37
  module.exports = __toCommonJS(modelUtils_exports);
37
38
  var import_bundler_utils = require("@umijs/bundler-utils");
@@ -43,6 +44,12 @@ var import_fs = require("fs");
43
44
  var import_path = require("path");
44
45
  var import_plugin_utils = require("umi/plugin-utils");
45
46
  var import_astUtils = require("./astUtils");
47
+ function transformSync(content, opts) {
48
+ if (!opts.tsconfig && !opts.tsconfigRaw) {
49
+ opts.tsconfigRaw = { compilerOptions: { experimentalDecorators: true } };
50
+ }
51
+ return (0, import_esbuild.transformSync)(content, opts);
52
+ }
46
53
  function getNamespace(absFilePath, absSrcPath) {
47
54
  const relPath = (0, import_plugin_utils.winPath)((0, import_path.relative)((0, import_plugin_utils.winPath)(absSrcPath), (0, import_plugin_utils.winPath)(absFilePath)));
48
55
  const parts = relPath.split("/");
@@ -77,7 +84,7 @@ var Model = class {
77
84
  findDeps(sort) {
78
85
  const content = (0, import_fs.readFileSync)(this.file, "utf-8");
79
86
  const loader = (0, import_path.extname)(this.file).slice(1);
80
- const result = (0, import_esbuild.transformSync)(content, {
87
+ const result = transformSync(content, {
81
88
  loader,
82
89
  sourcemap: false,
83
90
  minify: false
@@ -167,7 +174,7 @@ var _ModelUtils = class {
167
174
  try {
168
175
  const ext = (0, import_path.extname)(file).slice(1);
169
176
  const loader = ext === "js" ? "jsx" : ext;
170
- result = (0, import_esbuild.transformSync)(content, {
177
+ result = transformSync(content, {
171
178
  loader,
172
179
  sourcemap: false,
173
180
  minify: false,
@@ -282,5 +289,6 @@ ModelUtils.topologicalSort = (models) => {
282
289
  0 && (module.exports = {
283
290
  Model,
284
291
  ModelUtils,
285
- getNamespace
292
+ getNamespace,
293
+ transformSync
286
294
  });
@@ -77,6 +77,10 @@ function patchMicroAppRouteComponent(routes: any[]) {
77
77
  }
78
78
 
79
79
  export async function render(oldRender: typeof noop) {
80
+ // 在 ssr 的场景下,直接返回旧的 render
81
+ if (typeof window === 'undefined') {
82
+ return oldRender();
83
+ }
80
84
  const runtimeOptions = await getMasterRuntime();
81
85
  let masterOptions: MasterOptions = {
82
86
  ...getMasterOptions(),
@@ -138,6 +142,10 @@ export async function render(oldRender: typeof noop) {
138
142
  }
139
143
 
140
144
  export function patchClientRoutes({ routes }: { routes: any[] }) {
145
+ // 在 ssr 的场景下,不执行主应用的 patchClientRoutes
146
+ if (typeof window === 'undefined') {
147
+ return;
148
+ }
141
149
  const microAppRoutes = [].concat(
142
150
  deepFilterLeafRoutes(routes),
143
151
  deepFilterLeafRoutes(microAppRuntimeRoutes),
@@ -3,6 +3,10 @@ import { createHistory } from '@@/core/history';
3
3
  import qiankunRender, { contextOptsStack } from './lifecycles';
4
4
 
5
5
  export function render(oldRender: any) {
6
+ // 在 ssr 的场景下,直接返回旧的 render
7
+ if (typeof window === 'undefined') {
8
+ return oldRender();
9
+ }
6
10
  return qiankunRender().then(oldRender);
7
11
  }
8
12
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umijs/plugins",
3
- "version": "4.0.0-canary.20240624.1",
3
+ "version": "4.0.0-canary.20240702.1",
4
4
  "description": "@umijs/plugins",
5
5
  "homepage": "https://github.com/umijs/umi/tree/master/packages/plugins#readme",
6
6
  "bugs": "https://github.com/umijs/umi/issues",
@@ -23,7 +23,6 @@
23
23
  "@ant-design/icons": "^4.7.0",
24
24
  "@ant-design/moment-webpack-plugin": "^0.0.3",
25
25
  "@ant-design/pro-components": "^2.0.1",
26
- "@module-federation/enhanced": "^0.1.13",
27
26
  "@tanstack/react-query": "^4.24.10",
28
27
  "@tanstack/react-query-devtools": "^4.24.10",
29
28
  "antd-dayjs-webpack-plugin": "^1.0.6",
@@ -46,12 +45,12 @@
46
45
  "styled-components": "6.1.1",
47
46
  "tslib": "^2",
48
47
  "warning": "^4.0.3",
49
- "@umijs/bundler-utils": "4.0.0-canary.20240624.1",
48
+ "@umijs/bundler-utils": "4.0.0-canary.20240702.1",
50
49
  "@umijs/valtio": "1.0.4"
51
50
  },
52
51
  "devDependencies": {
53
52
  "antd": "^4.24.1",
54
- "umi": "4.0.0-canary.20240624.1"
53
+ "umi": "4.0.0-canary.20240702.1"
55
54
  },
56
55
  "publishConfig": {
57
56
  "access": "public"
@@ -44,6 +44,11 @@ const getAntdConfig = () => {
44
44
  {{/appConfig}}
45
45
  },
46
46
  });
47
+ {{#modelPluginCompat}}
48
+ if (!cacheAntdConfig.theme) {
49
+ cacheAntdConfig.theme = {};
50
+ }
51
+ {{/modelPluginCompat}}
47
52
  }
48
53
  return cacheAntdConfig;
49
54
  }
package/dist/mf-v2.d.ts DELETED
@@ -1,52 +0,0 @@
1
- import { zod as z } from '@umijs/utils';
2
- import { IApi } from 'umi';
3
- export declare enum EVersion {
4
- v1 = "v1",
5
- v2 = "v2"
6
- }
7
- interface IOptions {
8
- standalone?: boolean;
9
- }
10
- export declare function configSchema(zod: typeof z): z.ZodObject<{
11
- name: z.ZodOptional<z.ZodString>;
12
- remotes: z.ZodOptional<z.ZodArray<z.ZodObject<{
13
- name: z.ZodString;
14
- entry: z.ZodString;
15
- }, "strip", z.ZodTypeAny, {
16
- name: string;
17
- entry: string;
18
- }, {
19
- name: string;
20
- entry: string;
21
- }>, "many">>;
22
- shared: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
23
- library: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
24
- remoteHash: z.ZodOptional<z.ZodBoolean>;
25
- version: z.ZodOptional<z.ZodEnum<[EVersion.v1, EVersion.v2]>>;
26
- overrideConfig: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
27
- }, "strip", z.ZodTypeAny, {
28
- name?: string | undefined;
29
- remotes?: {
30
- name: string;
31
- entry: string;
32
- }[] | undefined;
33
- shared?: Record<string, any> | undefined;
34
- library?: Record<string, any> | undefined;
35
- remoteHash?: boolean | undefined;
36
- version?: EVersion | undefined;
37
- overrideConfig?: Record<string, any> | undefined;
38
- }, {
39
- name?: string | undefined;
40
- remotes?: {
41
- name: string;
42
- entry: string;
43
- }[] | undefined;
44
- shared?: Record<string, any> | undefined;
45
- library?: Record<string, any> | undefined;
46
- remoteHash?: boolean | undefined;
47
- version?: EVersion | undefined;
48
- overrideConfig?: Record<string, any> | undefined;
49
- }>;
50
- declare const _default: (api: IApi, options?: IOptions) => void;
51
- export default _default;
52
- export declare function isValidIdentifyName(name: string): boolean;
package/dist/mf-v2.js DELETED
@@ -1,402 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
-
29
- // src/mf-v2.ts
30
- var mf_v2_exports = {};
31
- __export(mf_v2_exports, {
32
- EVersion: () => EVersion,
33
- configSchema: () => configSchema,
34
- default: () => mf_v2_default,
35
- isValidIdentifyName: () => isValidIdentifyName
36
- });
37
- module.exports = __toCommonJS(mf_v2_exports);
38
- var import_bundler_utils = require("@umijs/bundler-utils");
39
- var import_utils = require("@umijs/utils");
40
- var import_fs = require("fs");
41
- var import_path = __toESM(require("path"));
42
- var { isEmpty } = import_utils.lodash;
43
- var EVersion = /* @__PURE__ */ ((EVersion2) => {
44
- EVersion2["v1"] = "v1";
45
- EVersion2["v2"] = "v2";
46
- return EVersion2;
47
- })(EVersion || {});
48
- var LOGGER_LABEL = import_utils.chalk.bold.blue("[module-federation-v2]");
49
- function configSchema(zod) {
50
- return zod.object({
51
- name: zod.string(),
52
- remotes: zod.array(
53
- zod.object({
54
- name: zod.string(),
55
- entry: zod.string()
56
- })
57
- ),
58
- shared: zod.record(zod.any()),
59
- library: zod.record(zod.any()),
60
- remoteHash: zod.boolean(),
61
- version: zod.enum(["v1" /* v1 */, "v2" /* v2 */]),
62
- overrideConfig: zod.record(zod.any())
63
- }).partial();
64
- }
65
- var mf_v2_default = (api, options) => {
66
- const { standalone = true } = options || {};
67
- if (standalone) {
68
- api.describe({
69
- key: "mfV2",
70
- enableBy: api.EnableBy.config,
71
- config: {
72
- schema({ zod }) {
73
- return configSchema(zod);
74
- }
75
- }
76
- });
77
- }
78
- let bundlerWebpackPath;
79
- try {
80
- bundlerWebpackPath = import_path.default.dirname(
81
- require.resolve("@umijs/bundler-webpack/package.json")
82
- );
83
- } catch {
84
- }
85
- api.onStart(() => {
86
- if (!bundlerWebpackPath) {
87
- throw new Error(
88
- `Not found '@umijs/bundler-webpack', please check dependencies`
89
- );
90
- }
91
- const infoMsg = `Using module federation v2`;
92
- console.log(`${LOGGER_LABEL} ${import_utils.chalk.gray(infoMsg)}`);
93
- process.env.FEDERATION_WEBPACK_PATH = import_path.default.join(
94
- api.paths.absTmpPath,
95
- `plugin-${api.plugin.key}`,
96
- "webpack/lib/index.js"
97
- );
98
- });
99
- api.onGenerateFiles(({ isFirstTime }) => {
100
- if (!isFirstTime || !bundlerWebpackPath) {
101
- return;
102
- }
103
- const webpackPath = import_path.default.join(bundlerWebpackPath, "compiled/webpack");
104
- const deepImportPath = import_path.default.join(webpackPath, "deepImports.json");
105
- const deepImports = require(deepImportPath);
106
- deepImports.forEach((p) => {
107
- const content = `
108
- module.exports = require('${p}')
109
- `.trimStart();
110
- api.writeTmpFile({
111
- path: `${p}.js`,
112
- content
113
- });
114
- });
115
- const entryContent = `module.exports = require('webpack')`;
116
- api.writeTmpFile({
117
- path: "webpack/lib/index.js",
118
- content: entryContent
119
- });
120
- });
121
- const getConfig = () => {
122
- const key = api.plugin.key;
123
- const config = api.userConfig[key] || api.config[key] || {};
124
- return config;
125
- };
126
- const constructExposes = async () => {
127
- const exposes = {};
128
- const exposesPath = import_path.default.join(api.paths.absSrcPath, "exposes");
129
- if (!(0, import_fs.existsSync)(exposesPath)) {
130
- return exposes;
131
- }
132
- const dir = (0, import_fs.opendirSync)(exposesPath);
133
- for await (const dirent of dir) {
134
- if (dirent.isDirectory()) {
135
- exposes[`./${dirent.name}`] = (0, import_utils.winPath)(
136
- import_path.default.join(exposesPath, dirent.name)
137
- );
138
- } else {
139
- const warningMsg = `${dirent.name} is not a directory, ignore in ModuleFederation expose`;
140
- console.log(`${LOGGER_LABEL} ${import_utils.chalk.yellow(warningMsg)}`);
141
- }
142
- }
143
- return exposes;
144
- };
145
- const formatRemotes = (config) => {
146
- const { remotes = [] } = config;
147
- const memo = {};
148
- remotes.forEach((remote) => {
149
- const { name, entry } = remote;
150
- if (!(name == null ? void 0 : name.length)) {
151
- const errorMsg = `remote name is required`;
152
- console.log(`${LOGGER_LABEL} ${import_utils.chalk.red(errorMsg)}`);
153
- throw new Error(errorMsg);
154
- }
155
- const getFormatEntry = () => {
156
- if (!(entry == null ? void 0 : entry.length)) {
157
- const errorMsg = `you should provider entry for remote ${name}`;
158
- console.log(`${LOGGER_LABEL} ${import_utils.chalk.red(errorMsg)}`);
159
- throw new Error(errorMsg);
160
- }
161
- const hasAt = entry.includes("@");
162
- if (hasAt) {
163
- return entry;
164
- }
165
- return `${remote.name}@${entry}`;
166
- };
167
- const finalName = name;
168
- const finalEntry = getFormatEntry();
169
- if (memo[finalName]) {
170
- const errorMsg = `remote ${finalName} is already exists, please check your config`;
171
- console.log(`${LOGGER_LABEL} ${import_utils.chalk.red(errorMsg)}`);
172
- throw new Error(errorMsg);
173
- }
174
- memo[finalName] = finalEntry;
175
- });
176
- return memo;
177
- };
178
- const getShared = (config) => {
179
- const { shared = {} } = config;
180
- return shared;
181
- };
182
- const mfAsyncEntryFileName = "asyncEntry.ts";
183
- const getAppEntryFile = () => {
184
- const entryFile = import_path.default.join(
185
- api.paths.absTmpPath,
186
- `plugin-${api.plugin.key}`,
187
- mfAsyncEntryFileName
188
- );
189
- return (0, import_utils.winPath)(entryFile);
190
- };
191
- const changeUmiEntry = (config) => {
192
- const { entry } = config;
193
- const asyncEntryPath = getAppEntryFile();
194
- if (entry.umi) {
195
- if (typeof entry.umi === "string") {
196
- entry.umi = asyncEntryPath;
197
- } else if (Array.isArray(entry.umi)) {
198
- const i = entry.umi.findIndex((f) => f.endsWith("umi.ts"));
199
- if (i >= 0) {
200
- entry.umi[i] = asyncEntryPath;
201
- } else {
202
- const warnMsg = `Not found umi entry in 'entry.umi' ${JSON.stringify(
203
- entry.umi
204
- )}`;
205
- console.log(`${LOGGER_LABEL} ${import_utils.chalk.yellow(warnMsg)}`);
206
- }
207
- }
208
- } else {
209
- const warnMsg = `umi entry not found`;
210
- console.log(`${LOGGER_LABEL} ${import_utils.chalk.yellow(warnMsg)}`);
211
- }
212
- };
213
- const getMfName = (config) => {
214
- const name = config.name;
215
- const packageName = api.pkg.name;
216
- const finalName = name || packageName;
217
- if (!(finalName == null ? void 0 : finalName.length)) {
218
- const errorMsg = `module federation name is not defined , please set 'name' in mf config or 'name' in package.json`;
219
- console.log(`${LOGGER_LABEL} ${import_utils.chalk.red(errorMsg)}`);
220
- throw new Error(errorMsg);
221
- }
222
- if (!isValidIdentifyName(finalName)) {
223
- throw new Error(
224
- `module federation name '${finalName}' is not valid javascript identifier.`
225
- );
226
- }
227
- return finalName;
228
- };
229
- api.modifyWebpackConfig(async (config) => {
230
- const pluginConfig = getConfig();
231
- const exposes = await constructExposes();
232
- const remotes = formatRemotes(pluginConfig);
233
- const shared = getShared(pluginConfig);
234
- if (isEmpty(remotes) && isEmpty(exposes)) {
235
- const warnMsg = `ModuleFederation exposes and remotes are empty, plugin will not work`;
236
- console.log(`${LOGGER_LABEL} ${import_utils.chalk.yellow(warnMsg)}`);
237
- return config;
238
- }
239
- if (api.env === "production" || !api.config.mfsu) {
240
- changeUmiEntry(config);
241
- }
242
- const name = getMfName(pluginConfig);
243
- const useHash = typeof pluginConfig.remoteHash === "boolean" ? pluginConfig.remoteHash : api.config.hash && api.env !== "development";
244
- const mfConfig = {
245
- name,
246
- remotes,
247
- filename: useHash ? "remote.[contenthash:8].js" : "remote.js",
248
- exposes,
249
- shared,
250
- library: pluginConfig.library,
251
- ...pluginConfig.overrideConfig || {}
252
- };
253
- const checkConfig = () => {
254
- if (api.config.mfsu) {
255
- console.log(
256
- `${LOGGER_LABEL} cannot use mfsu with module federation, please disable 'mfsu' in config (e.g. 'mfsu: false')`
257
- );
258
- throw new Error(`mfsu cannot use with module federation`);
259
- }
260
- if (!isEmpty(mfConfig.exposes)) {
261
- const jsMinifier = api.config.jsMinifier || "esbuild";
262
- if (jsMinifier === "esbuild") {
263
- const library = pluginConfig.library;
264
- if (!(library == null ? void 0 : library.type)) {
265
- const errorMsg = `mf config 'library.type' is required when not set 'jsMinifier' or use 'esbuild'`;
266
- const recommandMsg = `please set 'library.type' or use 'jsMinifier: terser' (e.g. 'library: { type: "window", name: "..." }')`;
267
- const finalMsg = `${errorMsg}, ${recommandMsg}`;
268
- console.log(`${LOGGER_LABEL} ${import_utils.chalk.red(finalMsg)}`);
269
- throw new Error(finalMsg);
270
- }
271
- }
272
- }
273
- };
274
- checkConfig();
275
- const {
276
- ModuleFederationPlugin
277
- } = require("@module-federation/enhanced/webpack");
278
- config.plugins.push(new ModuleFederationPlugin(mfConfig));
279
- api.logger.debug(
280
- `ModuleFederationPlugin V2 is enabled with config ${JSON.stringify(
281
- mfConfig
282
- )}`
283
- );
284
- return config;
285
- });
286
- api.register({
287
- key: "onGenerateFiles",
288
- stage: 10002,
289
- fn: async () => {
290
- const entry = import_path.default.join(api.paths.absTmpPath, "umi.ts");
291
- const content = (0, import_fs.readFileSync)(entry, "utf-8");
292
- const [_imports, exports] = await (0, import_bundler_utils.parseModule)({ content, path: entry });
293
- const mfEntryContent = [];
294
- let hasDefaultExport = false;
295
- if (exports.length) {
296
- mfEntryContent.push(
297
- `const umiExports = await import('${(0, import_utils.winPath)(entry)}')`
298
- );
299
- for (const exportName of exports) {
300
- if (exportName === "default") {
301
- hasDefaultExport = true;
302
- mfEntryContent.push(`export default umiExports.${exportName}`);
303
- } else {
304
- mfEntryContent.push(
305
- `export const ${exportName} = umiExports.${exportName}`
306
- );
307
- }
308
- }
309
- } else {
310
- mfEntryContent.push(`import('${(0, import_utils.winPath)(entry)}')`);
311
- }
312
- if (!hasDefaultExport) {
313
- mfEntryContent.push("export default 1");
314
- }
315
- api.writeTmpFile({
316
- content: mfEntryContent.join("\n"),
317
- path: mfAsyncEntryFileName
318
- });
319
- }
320
- });
321
- api.modifyTSConfig((memo) => {
322
- const typesDir = (0, import_utils.winPath)(import_path.default.join(api.cwd, "./@mf-types/*"));
323
- memo.compilerOptions.paths["*"] = [typesDir];
324
- return memo;
325
- });
326
- };
327
- function isValidIdentifyName(name) {
328
- const reservedKeywords = [
329
- "abstract",
330
- "await",
331
- "boolean",
332
- "break",
333
- "byte",
334
- "case",
335
- "catch",
336
- "char",
337
- "class",
338
- "const",
339
- "continue",
340
- "debugger",
341
- "default",
342
- "delete",
343
- "do",
344
- "double",
345
- "else",
346
- "enum",
347
- "export",
348
- "extends",
349
- "false",
350
- "final",
351
- "finally",
352
- "float",
353
- "for",
354
- "function",
355
- "goto",
356
- "if",
357
- "implements",
358
- "import",
359
- "in",
360
- "instanceof",
361
- "int",
362
- "interface",
363
- "let",
364
- "long",
365
- "native",
366
- "new",
367
- "null",
368
- "package",
369
- "private",
370
- "protected",
371
- "public",
372
- "return",
373
- "short",
374
- "static",
375
- "super",
376
- "switch",
377
- "synchronized",
378
- "this",
379
- "throw",
380
- "transient",
381
- "true",
382
- "try",
383
- "typeof",
384
- "var",
385
- "void",
386
- "volatile",
387
- "while",
388
- "with",
389
- "yield"
390
- ];
391
- const regexIdentifierName = /^(?:[$_\p{ID_Start}])(?:[$_\u200C\u200D\p{ID_Continue}])*$/u;
392
- if (reservedKeywords.includes(name) || !regexIdentifierName.test(name)) {
393
- return false;
394
- }
395
- return true;
396
- }
397
- // Annotate the CommonJS export names for ESM import in node:
398
- 0 && (module.exports = {
399
- EVersion,
400
- configSchema,
401
- isValidIdentifyName
402
- });