@umijs/plugins 4.0.0-beta.13 → 4.0.0-beta.14

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.
Files changed (36) hide show
  1. package/README.md +4 -1
  2. package/dist/dva.js +1 -1
  3. package/dist/layout.js +17 -8
  4. package/dist/locale.d.ts +1 -0
  5. package/dist/locale.js +199 -1
  6. package/dist/qiankun/constants.d.ts +5 -0
  7. package/dist/qiankun/constants.js +8 -0
  8. package/dist/qiankun/master.d.ts +6 -0
  9. package/dist/qiankun/master.js +116 -0
  10. package/dist/qiankun/slave.d.ts +3 -0
  11. package/dist/qiankun/slave.js +142 -0
  12. package/dist/qiankun.js +15 -1
  13. package/dist/request.js +293 -1
  14. package/dist/utils/localeUtils.d.ts +33 -0
  15. package/dist/utils/localeUtils.js +135 -0
  16. package/dist/utils/modelUtils.d.ts +1 -0
  17. package/dist/utils/modelUtils.js +17 -3
  18. package/libs/locale/SelectLang.tpl +478 -0
  19. package/libs/locale/locale.tpl +82 -0
  20. package/libs/locale/localeExports.tpl +271 -0
  21. package/libs/locale/runtime.tpl +33 -0
  22. package/libs/qiankun/master/AntdErrorBoundary.tsx +34 -0
  23. package/libs/qiankun/master/AntdLoader.tsx +15 -0
  24. package/libs/qiankun/master/ErrorBoundary.tsx +7 -0
  25. package/libs/qiankun/master/MicroApp.tsx +262 -0
  26. package/libs/qiankun/master/MicroAppWithMemoHistory.tsx +43 -0
  27. package/libs/qiankun/master/common.ts +133 -0
  28. package/libs/qiankun/master/constants.ts +7 -0
  29. package/libs/qiankun/master/getMicroAppRouteComponent.tsx.tpl +45 -0
  30. package/libs/qiankun/master/masterRuntimePlugin.tsx +133 -0
  31. package/libs/qiankun/master/types.ts +44 -0
  32. package/libs/qiankun/slave/connectMaster.tsx +15 -0
  33. package/libs/qiankun/slave/lifecycles.ts +149 -0
  34. package/libs/qiankun/slave/qiankunModel.ts +19 -0
  35. package/libs/qiankun/slave/slaveRuntimePlugin.ts +21 -0
  36. package/package.json +12 -4
package/README.md CHANGED
@@ -1,3 +1,6 @@
1
1
  # @umijs/plugins
2
2
 
3
- See our website [umijs](https://umijs.org) for more information.
3
+ See our website [umijs](https://umijs.org) for more information.
4
+
5
+
6
+
package/dist/dva.js CHANGED
@@ -47,7 +47,7 @@ exports.default = (api) => {
47
47
  });
48
48
  api.modifyConfig((memo) => {
49
49
  // import from dva
50
- memo.alias.dva = pkgPath;
50
+ memo.alias['dva$'] = pkgPath;
51
51
  return memo;
52
52
  });
53
53
  api.onGenerateFiles((args) => {
package/dist/layout.js CHANGED
@@ -203,13 +203,13 @@ export function patchRoutes({ routes }) {
203
203
  }
204
204
  `,
205
205
  });
206
- // rightRender.tsx
207
- api.writeTmpFile({
208
- path: 'rightRender.tsx',
209
- content: `
206
+ const rightRenderContent = `
210
207
  import React from 'react';
211
208
  import { Avatar, Dropdown, Menu, Spin } from 'antd';
212
209
  import { LogoutOutlined } from '@ant-design/icons';
210
+ {{#Locale}}
211
+ import { SelectLang } from '@@/plugin-locale';
212
+ {{/Locale}}
213
213
 
214
214
  export function getRightRenderContent (opts: {
215
215
  runtimeConfig: any,
@@ -257,7 +257,7 @@ export function getRightRenderContent (opts: {
257
257
  if (opts.loading) {
258
258
  return (
259
259
  <div className="umi-plugin-layout-right">
260
- <Spin size="small" style={{ marginLeft: 8, marginRight: 8 }} />
260
+ <Spin size="small" style={ { marginLeft: 8, marginRight: 8 } } />
261
261
  </div>
262
262
  );
263
263
  }
@@ -271,11 +271,20 @@ export function getRightRenderContent (opts: {
271
271
  ) : (
272
272
  avatar
273
273
  )}
274
+ {{#Locale}}
275
+ <SelectLang />
276
+ {{/Locale}}
274
277
  </div>
275
278
  );
276
- // TODO: <SelectLang />
277
279
  }
278
- `,
280
+ `;
281
+ const Locale = api.isPluginEnable('locale');
282
+ // rightRender.tsx
283
+ api.writeTmpFile({
284
+ path: 'rightRender.tsx',
285
+ content: plugin_utils_1.Mustache.render(rightRenderContent, {
286
+ Locale,
287
+ }),
279
288
  });
280
289
  // Layout.less
281
290
  api.writeTmpFile({
@@ -301,7 +310,7 @@ export function getRightRenderContent (opts: {
301
310
  }
302
311
  }
303
312
  .umi-plugin-layout-right {
304
- display: flex;
313
+ display: flex !important;
305
314
  float: right;
306
315
  height: 100%;
307
316
  margin-left: auto;
package/dist/locale.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  import { IApi } from 'umi';
2
+ export declare const packageNormalize: (packageName: string) => string;
2
3
  declare const _default: (api: IApi) => void;
3
4
  export default _default;
package/dist/locale.js CHANGED
@@ -1,5 +1,203 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.packageNormalize = void 0;
13
+ const utils_1 = require("@umijs/utils");
14
+ const fs_1 = require("fs");
15
+ const path_1 = require("path");
16
+ const localeUtils_1 = require("./utils/localeUtils");
17
+ const withTmpPath_1 = require("./utils/withTmpPath");
18
+ const packageNormalize = (packageName) => packageName.replace(/[@\/\-.]/g, '_');
19
+ exports.packageNormalize = packageNormalize;
20
+ // TODO: runtime plugin
3
21
  exports.default = (api) => {
4
- api;
22
+ var _a;
23
+ // TODO: antd 的校验考虑 antd 插件
24
+ let hasAntd = false;
25
+ try {
26
+ hasAntd = !!require.resolve('antd');
27
+ }
28
+ catch (e) {
29
+ api.logger.warn('antd is not installed. <SelecLang /> unavailable');
30
+ }
31
+ api.describe({
32
+ key: 'locale',
33
+ config: {
34
+ default: {
35
+ baseNavigator: true,
36
+ useLocalStorage: true,
37
+ baseSeparator: '-',
38
+ antd: hasAntd,
39
+ },
40
+ schema(joi) {
41
+ return joi.object({
42
+ default: joi.string(),
43
+ useLocalStorage: joi.boolean(),
44
+ baseNavigator: joi.boolean(),
45
+ title: joi.boolean(),
46
+ antd: joi.boolean(),
47
+ baseSeparator: joi.string(),
48
+ });
49
+ },
50
+ },
51
+ enableBy: api.EnableBy.config,
52
+ });
53
+ const reactIntlPkgPath = (0, path_1.dirname)(require.resolve('react-intl/package'));
54
+ // polyfill
55
+ if ((0, localeUtils_1.isNeedPolyfill)(((_a = api.userConfig) === null || _a === void 0 ? void 0 : _a.targets) || {})) {
56
+ api.addEntryImportsAhead(() => [
57
+ {
58
+ source: require.resolve('intl'),
59
+ },
60
+ ]);
61
+ }
62
+ const addAntdLocales = (args) => __awaiter(void 0, void 0, void 0, function* () {
63
+ var _b;
64
+ return yield api.applyPlugins({
65
+ key: 'addAntdLocales',
66
+ type: api.ApplyPluginsType.add,
67
+ initialValue: [
68
+ `antd/${((_b = api.config) === null || _b === void 0 ? void 0 : _b.ssr) ? 'lib' : 'es'}/locale/${(0, localeUtils_1.getAntdLocale)(args.lang, args.country)}`,
69
+ ],
70
+ args,
71
+ });
72
+ });
73
+ const getList = (resolveKey) => __awaiter(void 0, void 0, void 0, function* () {
74
+ var _c, _d;
75
+ const { paths } = api;
76
+ return (0, localeUtils_1.getLocaleList)({
77
+ localeFolder: ((_c = api.config) === null || _c === void 0 ? void 0 : _c.singular) ? 'locale' : 'locales',
78
+ separator: (_d = api.config.locale) === null || _d === void 0 ? void 0 : _d.baseSeparator,
79
+ absSrcPath: paths.absSrcPath,
80
+ absPagesPath: paths.absPagesPath,
81
+ addAntdLocales,
82
+ resolveKey,
83
+ });
84
+ });
85
+ api.onGenerateFiles(() => __awaiter(void 0, void 0, void 0, function* () {
86
+ var _e, _f, _g, _h;
87
+ const localeTpl = (0, fs_1.readFileSync)((0, path_1.join)(__dirname, '../libs/locale/locale.tpl'), 'utf-8');
88
+ // moment2dayjs
89
+ const resolveKey = api.config.moment2dayjs ? 'dayjs' : 'moment';
90
+ const momentPkgPath = (0, path_1.dirname)(require.resolve(`${resolveKey}/package.json`));
91
+ const EventEmitterPkg = (0, path_1.dirname)(require.resolve('event-emitter/package'));
92
+ const { baseSeparator, baseNavigator, antd, title, useLocalStorage } = api
93
+ .config.locale;
94
+ const defaultLocale = ((_e = api.config.locale) === null || _e === void 0 ? void 0 : _e.default) || `zh${baseSeparator}CN`;
95
+ const localeList = yield getList(resolveKey);
96
+ const momentLocales = localeList
97
+ .map(({ momentLocale }) => momentLocale)
98
+ .filter((locale) => locale);
99
+ const antdLocales = localeList
100
+ .map(({ antdLocale }) => antdLocale)
101
+ .filter((locale) => locale);
102
+ let MomentLocales = momentLocales;
103
+ let DefaultMomentLocale = '';
104
+ // set moment default accounding to locale.default
105
+ if (!MomentLocales.length && ((_f = api.config.locale) === null || _f === void 0 ? void 0 : _f.default)) {
106
+ const [lang, country = ''] = defaultLocale.split(baseSeparator);
107
+ const { momentLocale } = (0, localeUtils_1.getMomentLocale)(lang, country, resolveKey);
108
+ if (momentLocale) {
109
+ MomentLocales = [momentLocale];
110
+ DefaultMomentLocale = momentLocale;
111
+ }
112
+ }
113
+ let DefaultAntdLocales = [];
114
+ // set antd default locale
115
+ if (!antdLocales.length && ((_g = api.config.locale) === null || _g === void 0 ? void 0 : _g.antd)) {
116
+ const [lang, country = ''] = defaultLocale.split(baseSeparator);
117
+ DefaultAntdLocales = utils_1.lodash.uniq(yield addAntdLocales({
118
+ lang,
119
+ country,
120
+ }));
121
+ }
122
+ const NormalizeAntdLocalesName = function () {
123
+ // @ts-ignore
124
+ return (0, exports.packageNormalize)(this);
125
+ };
126
+ api.writeTmpFile({
127
+ content: utils_1.Mustache.render(localeTpl, {
128
+ MomentLocales,
129
+ DefaultMomentLocale,
130
+ NormalizeAntdLocalesName,
131
+ DefaultAntdLocales,
132
+ Antd: !!antd,
133
+ Title: title && api.config.title,
134
+ BaseSeparator: baseSeparator,
135
+ DefaultLocale: defaultLocale,
136
+ DefaultLang: defaultLocale,
137
+ momentPkgPath,
138
+ }),
139
+ path: 'locale.tsx',
140
+ });
141
+ const localeExportsTpl = (0, fs_1.readFileSync)((0, path_1.join)(__dirname, '../libs/locale/localeExports.tpl'), 'utf-8');
142
+ const localeDirName = api.config.singular ? 'locale' : 'locales';
143
+ const localeDirPath = (0, path_1.join)(api.paths.absSrcPath, localeDirName);
144
+ api.writeTmpFile({
145
+ path: 'localeExports.ts',
146
+ content: utils_1.Mustache.render(localeExportsTpl, {
147
+ EventEmitterPkg,
148
+ BaseSeparator: baseSeparator,
149
+ BaseNavigator: baseNavigator,
150
+ UseLocalStorage: !!useLocalStorage,
151
+ LocaleDir: localeDirName,
152
+ ExistLocaleDir: (0, fs_1.existsSync)(localeDirPath),
153
+ LocaleList: localeList.map((locale) => (Object.assign(Object.assign({}, locale), { antdLocale: locale.antdLocale.map((antdLocale, index) => ({
154
+ locale: antdLocale,
155
+ index: index,
156
+ })), paths: locale.paths.map((path, index) => ({
157
+ path,
158
+ index,
159
+ })) }))),
160
+ Antd: !!antd,
161
+ DefaultLocale: JSON.stringify(defaultLocale),
162
+ warningPkgPath: require.resolve('warning/package'),
163
+ reactIntlPkgPath,
164
+ }),
165
+ });
166
+ // runtime.tsx
167
+ const runtimeTpl = (0, fs_1.readFileSync)((0, path_1.join)(__dirname, '../libs/locale/runtime.tpl'), 'utf-8');
168
+ api.writeTmpFile({
169
+ path: 'runtime.tsx',
170
+ content: utils_1.Mustache.render(runtimeTpl, {
171
+ Title: !!title,
172
+ }),
173
+ });
174
+ // SelectLang.tsx
175
+ const selectLang = (0, fs_1.readFileSync)((0, path_1.join)(__dirname, '../libs/locale/SelectLang.tpl'), 'utf-8');
176
+ api.writeTmpFile({
177
+ path: 'SelectLang.tsx',
178
+ content: utils_1.Mustache.render(selectLang, {
179
+ Antd: !!antd,
180
+ LocaleList: localeList,
181
+ ShowSelectLang: localeList.length > 1 && !!antd,
182
+ antdFiles: ((_h = api.config) === null || _h === void 0 ? void 0 : _h.ssr) ? 'lib' : 'es',
183
+ }),
184
+ });
185
+ // index.ts
186
+ api.writeTmpFile({
187
+ path: 'index.ts',
188
+ content: `
189
+ export * from './localeExports.ts';
190
+ export * from './SelectLang.tsx';
191
+ `,
192
+ });
193
+ }));
194
+ // Runtime Plugin
195
+ api.addRuntimePlugin(() => [(0, withTmpPath_1.withTmpPath)({ api, path: 'runtime.tsx' })]);
196
+ api.addRuntimePluginKey(() => ['locale']);
197
+ // watch locale files
198
+ api.addTmpGenerateWatcherPaths(() => __awaiter(void 0, void 0, void 0, function* () {
199
+ const resolveKey = api.config.moment2dayjs ? 'dayjs' : 'moment';
200
+ const localeList = yield getList(resolveKey);
201
+ return (0, localeUtils_1.exactLocalePaths)(localeList);
202
+ }));
5
203
  };
@@ -0,0 +1,5 @@
1
+ export declare const defaultMasterRootId = "root-master";
2
+ export declare const defaultHistoryType = "browser";
3
+ export declare const qiankunStateForSlaveModelNamespace = "@@qiankunStateForSlave";
4
+ export declare const qiankunStateFromMasterModelNamespace = "@@qiankunStateFromMaster";
5
+ export declare const MODEL_EXPORT_NAME = "useQiankunStateForSlave";
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MODEL_EXPORT_NAME = exports.qiankunStateFromMasterModelNamespace = exports.qiankunStateForSlaveModelNamespace = exports.defaultHistoryType = exports.defaultMasterRootId = void 0;
4
+ exports.defaultMasterRootId = 'root-master';
5
+ exports.defaultHistoryType = 'browser';
6
+ exports.qiankunStateForSlaveModelNamespace = '@@qiankunStateForSlave';
7
+ exports.qiankunStateFromMasterModelNamespace = '@@qiankunStateFromMaster';
8
+ exports.MODEL_EXPORT_NAME = 'useQiankunStateForSlave';
@@ -0,0 +1,6 @@
1
+ import { IApi } from 'umi';
2
+ export declare function isMasterEnable(opts: {
3
+ userConfig: any;
4
+ }): boolean;
5
+ declare const _default: (api: IApi) => void;
6
+ export default _default;
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isMasterEnable = void 0;
4
+ const fs_1 = require("fs");
5
+ const path_1 = require("path");
6
+ const withTmpPath_1 = require("../utils/withTmpPath");
7
+ const constants_1 = require("./constants");
8
+ function isMasterEnable(opts) {
9
+ var _a;
10
+ const masterCfg = (_a = opts.userConfig.qiankun) === null || _a === void 0 ? void 0 : _a.master;
11
+ if (masterCfg) {
12
+ return masterCfg.enable !== false;
13
+ }
14
+ return !!process.env.INITIAL_QIANKUN_MASTER_OPTIONS;
15
+ }
16
+ exports.isMasterEnable = isMasterEnable;
17
+ exports.default = (api) => {
18
+ api.describe({
19
+ key: 'qiankun-master',
20
+ enableBy: isMasterEnable,
21
+ });
22
+ api.addRuntimePlugin(() => {
23
+ return [(0, withTmpPath_1.withTmpPath)({ api, path: 'masterRuntimePlugin.tsx' })];
24
+ });
25
+ api.modifyDefaultConfig((config) => (Object.assign(Object.assign({}, config), {
26
+ // TODO: support mountElementId
27
+ mountElementId: constants_1.defaultMasterRootId, qiankun: Object.assign(Object.assign({}, config.qiankun), { master: Object.assign(Object.assign({}, JSON.parse(process.env.INITIAL_QIANKUN_MASTER_OPTIONS || '{}')), (config.qiankun || {}).master) }) })));
28
+ // TODO: modify routes
29
+ api.modifyRoutes((memo) => {
30
+ Object.keys(memo).forEach((id) => {
31
+ const route = memo[id];
32
+ if (route.microApp) {
33
+ const appName = route.microApp;
34
+ // TODO: config base
35
+ const base = '/';
36
+ // TODO: config masterHistoryType
37
+ const masterHistoryType = 'browser';
38
+ const routeProps = route.microAppProps || {};
39
+ const normalizedRouteProps = JSON.stringify(routeProps).replace(/"/g, "'");
40
+ route.file = `(async () => {
41
+ const { getMicroAppRouteComponent } = await import('@@/plugin-qiankun-master/getMicroAppRouteComponent');
42
+ return getMicroAppRouteComponent({ appName: '${appName}', base: '${base}', masterHistoryType: '${masterHistoryType}', routeProps: ${normalizedRouteProps} })
43
+ })()`;
44
+ }
45
+ });
46
+ return memo;
47
+ });
48
+ // state model for slave app
49
+ api.addRuntimePluginKey(() => [constants_1.MODEL_EXPORT_NAME]);
50
+ api.register({
51
+ key: 'addExtraModels',
52
+ fn() {
53
+ const [path, exports] = api.appData.appJS || [];
54
+ return path && exports.includes(constants_1.MODEL_EXPORT_NAME)
55
+ ? [
56
+ `${path}#{"namespace":"${constants_1.qiankunStateForSlaveModelNamespace}","exportName":"${constants_1.MODEL_EXPORT_NAME}"}`,
57
+ ]
58
+ : [];
59
+ },
60
+ });
61
+ function getFileContent(file) {
62
+ return (0, fs_1.readFileSync)((0, path_1.join)(__dirname, '../../libs/qiankun/master', file), 'utf-8');
63
+ }
64
+ api.onGenerateFiles(() => {
65
+ var _a;
66
+ api.writeTmpFile({
67
+ path: 'masterOptions.ts',
68
+ content: `
69
+ let options = ${JSON.stringify(Object.assign({ masterHistoryType: ((_a = api.config.history) === null || _a === void 0 ? void 0 : _a.type) || constants_1.defaultHistoryType, base: api.config.base || '/' }, api.config.qiankun.master))};
70
+ export const getMasterOptions = () => options;
71
+ export const setMasterOptions = (newOpts) => options = ({ ...options, ...newOpts });
72
+ `,
73
+ });
74
+ api.writeTmpFile({
75
+ path: 'MicroAppLoader.tsx',
76
+ // 开启了 antd 插件的时候,使用 antd 的 loader 组件,否则提示用户必须设置一个自定义的 loader 组件
77
+ content: api.isPluginEnable('antd')
78
+ ? getFileContent('AntdLoader.tsx')
79
+ : `export default function Loader() { console.warn(\`[plugins/qiankun]: Seems like you'r not using @umijs/plugin-antd, you need to provide a custom loader or set autoSetLoading false to shut down this warning!\`); return null; }`,
80
+ });
81
+ [
82
+ 'common.ts',
83
+ 'constants.ts',
84
+ 'types.ts',
85
+ 'masterRuntimePlugin.tsx',
86
+ 'getMicroAppRouteComponent.tsx.tpl',
87
+ 'ErrorBoundary.tsx',
88
+ 'MicroApp.tsx',
89
+ ].forEach((file) => {
90
+ if (file.endsWith('.tpl')) {
91
+ api.writeTmpFile({
92
+ path: file.replace(/\.tpl$/, ''),
93
+ tpl: getFileContent(file),
94
+ context: {
95
+ runtimeHistory: api.config.runtimeHistory,
96
+ dynamicRoot: false,
97
+ hasModelPlugin: api.isPluginEnable('model'),
98
+ // dynamicRoot:
99
+ // api.config.exportStatic && api.config.exportStatic.dynamicRoot,
100
+ },
101
+ });
102
+ }
103
+ else {
104
+ api.writeTmpFile({
105
+ path: file.replace(/\.tpl$/, ''),
106
+ content: getFileContent(file)
107
+ .replace('__USE_MODEL__', api.isPluginEnable('model')
108
+ ? `import { useModel } from '@@/plugin-model'`
109
+ : `const useModel = null;`)
110
+ .replace(/from 'qiankun'/g, `from '${(0, path_1.dirname)(require.resolve('qiankun/package'))}'`)
111
+ .replace(/from 'lodash\//g, `from '${(0, path_1.dirname)(require.resolve('lodash/package'))}/`),
112
+ });
113
+ }
114
+ });
115
+ });
116
+ };
@@ -0,0 +1,3 @@
1
+ import { IApi } from 'umi';
2
+ declare const _default: (api: IApi) => void;
3
+ export default _default;
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const assert_1 = __importDefault(require("assert"));
7
+ const fs_1 = require("fs");
8
+ const path_1 = require("path");
9
+ const withTmpPath_1 = require("../utils/withTmpPath");
10
+ const constants_1 = require("./constants");
11
+ // BREAK CHANGE: 需要手动配置 slave: {},不能留空
12
+ function isSlaveEnable(opts) {
13
+ var _a, _b;
14
+ const slaveCfg = (_b = (_a = opts.userConfig) === null || _a === void 0 ? void 0 : _a.qiankun) === null || _b === void 0 ? void 0 : _b.slave;
15
+ if (slaveCfg) {
16
+ return slaveCfg.enable !== false;
17
+ }
18
+ return !!process.env.INITIAL_QIANKUN_SLAVE_OPTIONS;
19
+ }
20
+ exports.default = (api) => {
21
+ api.describe({
22
+ key: 'qiankun-slave',
23
+ enableBy: isSlaveEnable,
24
+ });
25
+ api.addRuntimePlugin(() => {
26
+ return [(0, withTmpPath_1.withTmpPath)({ api, path: 'slaveRuntimePlugin.ts' })];
27
+ });
28
+ api.register({
29
+ key: 'addExtraModels',
30
+ fn() {
31
+ return [
32
+ `@@/plugin-qiankun-slave/qiankunModel#{"namespace":"${constants_1.qiankunStateFromMasterModelNamespace}"}`,
33
+ ];
34
+ },
35
+ });
36
+ api.modifyDefaultConfig((memo) => {
37
+ var _a, _b, _c;
38
+ const initialSlaveOptions = Object.assign(Object.assign({ devSourceMap: true }, JSON.parse(process.env.INITIAL_QIANKUN_SLAVE_OPTIONS || '{}')), (memo.qiankun || {}).slave);
39
+ const modifiedDefaultConfig = Object.assign(Object.assign({}, memo), {
40
+ // 默认开启 runtimePublicPath,避免出现 dynamic import 场景子应用资源地址出问题
41
+ // TODO: runtimePublicPath
42
+ runtimePublicPath: true,
43
+ // TODO: runtimeHistory
44
+ runtimeHistory: {}, qiankun: Object.assign(Object.assign({}, memo.qiankun), { slave: initialSlaveOptions }) });
45
+ const shouldNotModifyDefaultBase = (_c = (_b = (_a = api.userConfig.qiankun) === null || _a === void 0 ? void 0 : _a.slave) === null || _b === void 0 ? void 0 : _b.shouldNotModifyDefaultBase) !== null && _c !== void 0 ? _c : initialSlaveOptions.shouldNotModifyDefaultBase;
46
+ if (!shouldNotModifyDefaultBase) {
47
+ // @ts-ignore
48
+ modifiedDefaultConfig.base = `/${api.pkg.name}`;
49
+ }
50
+ return modifiedDefaultConfig;
51
+ });
52
+ api.modifyConfig((config) => {
53
+ var _a, _b;
54
+ // mfsu 场景默认给子应用增加 mfName 配置,从而避免冲突
55
+ if (config.mfsu !== false) {
56
+ config.mfsu = Object.assign(Object.assign({}, config.mfsu), { mfName: ((_a = config.mfsu) === null || _a === void 0 ? void 0 : _a.mfName) ||
57
+ `mf_${(_b = api.pkg.name) === null || _b === void 0 ? void 0 : _b.replace(/^@/, '').replace(/\W/g, '_')}` });
58
+ }
59
+ return config;
60
+ });
61
+ // api.modifyPublicPathStr((publicPathStr) => {
62
+ // const { runtimePublicPath } = api.config;
63
+ // const { shouldNotModifyRuntimePublicPath } = (api.config.qiankun || {})
64
+ // .slave!;
65
+ // if (runtimePublicPath === true && !shouldNotModifyRuntimePublicPath) {
66
+ // return `window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ || "${
67
+ // api.config.publicPath || '/'
68
+ // }"`;
69
+ // }
70
+ // return publicPathStr;
71
+ // });
72
+ api.chainWebpack((config) => {
73
+ (0, assert_1.default)(api.pkg.name, 'You should have name in package.json.');
74
+ const { shouldNotAddLibraryChunkName } = (api.config.qiankun || {}).slave;
75
+ config.output
76
+ .libraryTarget('umd')
77
+ .library(shouldNotAddLibraryChunkName ? api.pkg.name : `${api.pkg.name}-[name]`);
78
+ // TODO: SOCKET_SERVER
79
+ // TODO: devSourceMap
80
+ return config;
81
+ });
82
+ // umi bundle 添加 entry 标记
83
+ api.modifyHTML(($) => {
84
+ $('script').each((_, el) => {
85
+ var _a;
86
+ const scriptEl = $(el);
87
+ const umiEntryJs = /\/?umi(\.\w+)?\.js$/g;
88
+ if (umiEntryJs.test((_a = scriptEl.attr('src')) !== null && _a !== void 0 ? _a : '')) {
89
+ scriptEl.attr('entry', '');
90
+ }
91
+ });
92
+ return $;
93
+ });
94
+ api.addEntryImports(() => {
95
+ return [
96
+ {
97
+ source: '@@/plugin-qiankun-slave/lifecycles',
98
+ specifier: '{ genMount as qiankun_genMount, genBootstrap as qiankun_genBootstrap, genUnmount as qiankun_genUnmount, genUpdate as qiankun_genUpdate }',
99
+ },
100
+ ];
101
+ });
102
+ api.addEntryCode(() => [
103
+ `
104
+ export const bootstrap = qiankun_genBootstrap(render);
105
+ export const mount = qiankun_genMount('${api.config.mountElementId}');
106
+ export const unmount = qiankun_genUnmount('${api.config.mountElementId}');
107
+ export const update = qiankun_genUpdate();
108
+ if (!window.__POWERED_BY_QIANKUN__) {
109
+ bootstrap().then(mount);
110
+ }
111
+ `,
112
+ ]);
113
+ function getFileContent(file) {
114
+ return (0, fs_1.readFileSync)((0, path_1.join)(__dirname, '../../libs/qiankun/slave', file), 'utf-8');
115
+ }
116
+ api.onGenerateFiles(() => {
117
+ // api.writeTmpFile({
118
+ // path: 'slaveOptions.ts',
119
+ // content: `
120
+ // let options = ${JSON.stringify((api.config.qiankun || {}).slave || {})};
121
+ // export const getSlaveOptions = () => options;
122
+ // export const setSlaveOptions = (newOpts) => options = ({ ...options, ...newOpts });
123
+ // `,
124
+ // });
125
+ [
126
+ 'qiankunModel.ts',
127
+ 'connectMaster.tsx',
128
+ 'slaveRuntimePlugin.ts',
129
+ 'lifecycles.ts',
130
+ ].forEach((file) => {
131
+ api.writeTmpFile({
132
+ path: file.replace(/\.tpl$/, ''),
133
+ content: getFileContent(file)
134
+ .replace('__USE_MODEL__', api.isPluginEnable('model')
135
+ ? `import { useModel } from '@@/plugin/model'`
136
+ : `const useModel = null;`)
137
+ .replace(/from 'qiankun'/g, `from '${(0, path_1.dirname)(require.resolve('qiankun/package'))}'`)
138
+ .replace(/from 'lodash\//g, `from '${(0, path_1.dirname)(require.resolve('lodash/package'))}/`),
139
+ });
140
+ });
141
+ });
142
+ };
package/dist/qiankun.js CHANGED
@@ -1,5 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.default = (api) => {
4
- api;
4
+ api.describe({
5
+ config: {
6
+ schema(joi) {
7
+ return joi.object().keys({
8
+ slave: joi.object(),
9
+ master: joi.object(),
10
+ });
11
+ },
12
+ },
13
+ });
14
+ api.addRuntimePluginKey(() => ['qiankun']);
15
+ api.registerPlugins([
16
+ require.resolve('./qiankun/master'),
17
+ require.resolve('./qiankun/slave'),
18
+ ]);
5
19
  };