@umijs/plugins 4.0.0-beta.9 → 4.0.0-canary.20220316.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.
Files changed (58) hide show
  1. package/README.md +4 -1
  2. package/dist/access.js +73 -1
  3. package/dist/{sass.d.ts → analytics.d.ts} +0 -0
  4. package/dist/analytics.js +67 -0
  5. package/dist/antd.js +101 -145
  6. package/dist/dva.d.ts +3 -0
  7. package/dist/dva.js +185 -4
  8. package/dist/initial-state.js +112 -1
  9. package/dist/layout.js +483 -1
  10. package/dist/locale.d.ts +1 -0
  11. package/dist/locale.js +199 -1
  12. package/dist/model.js +116 -1
  13. package/dist/moment2dayjs.d.ts +3 -0
  14. package/dist/moment2dayjs.js +96 -0
  15. package/dist/qiankun/constants.d.ts +5 -0
  16. package/dist/qiankun/constants.js +8 -0
  17. package/dist/qiankun/master.d.ts +6 -0
  18. package/dist/qiankun/master.js +115 -0
  19. package/dist/qiankun/slave.d.ts +3 -0
  20. package/dist/qiankun/slave.js +142 -0
  21. package/dist/qiankun.js +15 -1
  22. package/dist/request.js +300 -1
  23. package/dist/tailwindcss.d.ts +3 -0
  24. package/dist/tailwindcss.js +40 -0
  25. package/dist/unocss.d.ts +3 -0
  26. package/dist/unocss.js +39 -0
  27. package/dist/utils/astUtils.d.ts +3 -0
  28. package/dist/utils/astUtils.js +38 -0
  29. package/dist/utils/localeUtils.d.ts +33 -0
  30. package/dist/utils/localeUtils.js +135 -0
  31. package/dist/utils/modelUtils.d.ts +35 -0
  32. package/dist/utils/modelUtils.js +149 -0
  33. package/dist/utils/resolveProjectDep.d.ts +5 -0
  34. package/dist/utils/resolveProjectDep.js +15 -0
  35. package/dist/utils/withTmpPath.d.ts +6 -0
  36. package/dist/utils/withTmpPath.js +11 -0
  37. package/libs/dva.ts +10 -0
  38. package/libs/locale/SelectLang.tpl +478 -0
  39. package/libs/locale/locale.tpl +82 -0
  40. package/libs/locale/localeExports.tpl +271 -0
  41. package/libs/locale/runtime.tpl +33 -0
  42. package/libs/model.tsx +140 -0
  43. package/libs/qiankun/master/AntdErrorBoundary.tsx +34 -0
  44. package/libs/qiankun/master/AntdLoader.tsx +15 -0
  45. package/libs/qiankun/master/ErrorBoundary.tsx +7 -0
  46. package/libs/qiankun/master/MicroApp.tsx +262 -0
  47. package/libs/qiankun/master/MicroAppWithMemoHistory.tsx +43 -0
  48. package/libs/qiankun/master/common.ts +133 -0
  49. package/libs/qiankun/master/constants.ts +7 -0
  50. package/libs/qiankun/master/getMicroAppRouteComponent.tsx.tpl +45 -0
  51. package/libs/qiankun/master/masterRuntimePlugin.tsx +130 -0
  52. package/libs/qiankun/master/types.ts +44 -0
  53. package/libs/qiankun/slave/connectMaster.tsx +15 -0
  54. package/libs/qiankun/slave/lifecycles.ts +149 -0
  55. package/libs/qiankun/slave/qiankunModel.ts +19 -0
  56. package/libs/qiankun/slave/slaveRuntimePlugin.ts +21 -0
  57. package/package.json +24 -6
  58. package/dist/sass.js +0 -5
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/access.js CHANGED
@@ -1,5 +1,77 @@
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
+ const path_1 = require("path");
13
+ const withTmpPath_1 = require("./utils/withTmpPath");
3
14
  exports.default = (api) => {
4
- api;
15
+ // TODO: route access
16
+ api.describe({
17
+ config: {
18
+ schema(joi) {
19
+ return joi.object();
20
+ },
21
+ },
22
+ enableBy: api.EnableBy.config,
23
+ });
24
+ api.onGenerateFiles(() => __awaiter(void 0, void 0, void 0, function* () {
25
+ // runtime.tsx
26
+ api.writeTmpFile({
27
+ path: 'runtime.tsx',
28
+ content: `
29
+ import React from 'react';
30
+ import accessFactory from '@/access';
31
+ import { useModel } from '@@/plugin-model';
32
+ import { AccessContext } from './context';
33
+
34
+ function Provider(props) {
35
+ const { initialState } = useModel('@@initialState');
36
+ const access = React.useMemo(() => accessFactory(initialState), [initialState]);
37
+ return (
38
+ <AccessContext.Provider value={access}>
39
+ { props.children }
40
+ </AccessContext.Provider>
41
+ );
42
+ }
43
+
44
+ export function accessProvider(container) {
45
+ return <Provider>{ container }</Provider>;
46
+ }
47
+ `,
48
+ });
49
+ // index.ts
50
+ api.writeTmpFile({
51
+ path: 'index.ts',
52
+ content: `
53
+ import React from 'react';
54
+ import { AccessContext } from './context';
55
+
56
+ export const useAccess = () => {
57
+ return React.useContext(AccessContext);
58
+ };
59
+ `,
60
+ });
61
+ // context.ts
62
+ api.writeTmpFile({
63
+ path: 'context.ts',
64
+ content: `
65
+ import React from 'react';
66
+ export const AccessContext = React.createContext<any>(null);
67
+ `,
68
+ });
69
+ }));
70
+ api.addRuntimePlugin(() => {
71
+ return [(0, withTmpPath_1.withTmpPath)({ api, path: 'runtime.tsx' })];
72
+ });
73
+ api.addTmpGenerateWatcherPaths(() => [
74
+ (0, path_1.join)(api.paths.absSrcPath, 'access.ts'),
75
+ (0, path_1.join)(api.paths.absSrcPath, 'access.js'),
76
+ ]);
5
77
  };
File without changes
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = (api) => {
4
+ const GA_KEY = process.env.GA_KEY;
5
+ const enableBy = (opts) => {
6
+ return opts.config.analytics || GA_KEY;
7
+ };
8
+ api.describe({
9
+ key: 'analytics',
10
+ config: {
11
+ schema(joi) {
12
+ return joi.object();
13
+ },
14
+ onChange: api.ConfigChangeType.reload,
15
+ },
16
+ enableBy,
17
+ });
18
+ // https://tongji.baidu.com/web/help/article?id=174&type=0
19
+ const baiduTpl = (code) => {
20
+ return `
21
+ (function() {
22
+ var hm = document.createElement('script');
23
+ hm.src = 'https://hm.baidu.com/hm.js?${code}';
24
+ var s = document.getElementsByTagName('script')[0];
25
+ s.parentNode.insertBefore(hm, s);
26
+ })();
27
+ `;
28
+ };
29
+ const gaTpl = (code) => {
30
+ return `
31
+ (function(){
32
+ if (!location.port) {
33
+ (function (i, s, o, g, r, a, m) {
34
+ i['GoogleAnalyticsObject'] = r;
35
+ i[r] = i[r] || function () {
36
+ (i[r].q = i[r].q || []).push(arguments)
37
+ }, i[r].l = 1 * new Date();
38
+ a = s.createElement(o),
39
+ m = s.getElementsByTagName(o)[0];
40
+ a.async = 1;
41
+ a.src = g;
42
+ m.parentNode.insertBefore(a, m)
43
+ })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
44
+ ga('create', '${code}', 'auto');
45
+ ga('send', 'pageview');
46
+ }
47
+ })();
48
+ `;
49
+ };
50
+ api.addHTMLHeadScripts(() => {
51
+ const { analytics = {} } = api.config;
52
+ const { ga = GA_KEY, baidu } = analytics;
53
+ return [
54
+ baidu && {
55
+ content: 'var _hmt = _hmt || [];',
56
+ },
57
+ api.env !== 'development' &&
58
+ baidu && {
59
+ content: baiduTpl(baidu),
60
+ },
61
+ api.env !== 'development' &&
62
+ ga && {
63
+ content: gaTpl(ga),
64
+ },
65
+ ].filter(Boolean);
66
+ });
67
+ };
package/dist/antd.js CHANGED
@@ -1,169 +1,125 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const utils_1 = require("@umijs/utils");
4
- const fs_1 = require("fs");
5
3
  const path_1 = require("path");
6
- const presets = {
7
- antd: {
8
- plugins: [
9
- 'isSameOrBefore',
10
- 'isSameOrAfter',
11
- 'advancedFormat',
12
- 'customParseFormat',
13
- 'weekday',
14
- 'weekYear',
15
- 'weekOfYear',
16
- 'isMoment',
17
- 'localeData',
18
- 'localizedFormat',
19
- ],
20
- replaceMoment: true,
21
- },
22
- antdv3: {
23
- plugins: [
24
- 'isSameOrBefore',
25
- 'isSameOrAfter',
26
- 'advancedFormat',
27
- 'customParseFormat',
28
- 'weekday',
29
- 'weekYear',
30
- 'weekOfYear',
31
- 'isMoment',
32
- 'localeData',
33
- 'localizedFormat',
34
- 'badMutable',
35
- ],
36
- replaceMoment: true,
37
- },
38
- };
39
- const getConfig = (api) => {
40
- let { preset = 'antd', plugins, replaceMoment, } = api.userConfig.antdDayjs || {};
41
- if (preset && presets[preset]) {
42
- plugins = presets[preset].plugins;
43
- replaceMoment = presets[preset].replaceMoment;
44
- }
45
- if (plugins)
46
- plugins = plugins;
47
- if (replaceMoment !== undefined)
48
- replaceMoment = replaceMoment;
49
- return {
50
- plugins,
51
- replaceMoment,
52
- };
53
- };
54
- const DIR_NAME = 'plugin-antd';
4
+ const plugin_utils_1 = require("umi/plugin-utils");
5
+ const resolveProjectDep_1 = require("./utils/resolveProjectDep");
6
+ const withTmpPath_1 = require("./utils/withTmpPath");
55
7
  exports.default = (api) => {
56
- const opts = api.userConfig.antd;
57
- // dayjs (by default)
58
- const { dayjs = true } = opts;
8
+ let pkgPath;
9
+ try {
10
+ pkgPath =
11
+ (0, resolveProjectDep_1.resolveProjectDep)({
12
+ pkg: api.pkg,
13
+ cwd: api.cwd,
14
+ dep: 'antd',
15
+ }) || (0, path_1.dirname)(require.resolve('antd/package.json'));
16
+ }
17
+ catch (e) { }
59
18
  api.describe({
60
19
  config: {
61
20
  schema(Joi) {
62
21
  return Joi.object({
22
+ configProvider: Joi.object(),
23
+ // themes
63
24
  dark: Joi.boolean(),
64
25
  compact: Joi.boolean(),
65
- config: Joi.object(),
66
- dayjs: Joi.alternatives(Joi.boolean(), Joi.object({
67
- preset: Joi.string(),
68
- plugins: Joi.array(),
69
- replaceMoment: Joi.boolean(),
70
- })),
26
+ // babel-plugin-import
27
+ import: Joi.boolean(),
28
+ // less or css, default less
29
+ style: Joi.string().allow('less', 'css'),
71
30
  });
72
31
  },
73
32
  },
33
+ enableBy: api.EnableBy.config,
34
+ });
35
+ function checkPkgPath() {
36
+ if (!pkgPath) {
37
+ throw new Error(`Can't find antd package. Please install antd first.`);
38
+ }
39
+ }
40
+ api.modifyAppData((memo) => {
41
+ checkPkgPath();
42
+ const version = require(`${pkgPath}/package.json`).version;
43
+ memo.antd = {
44
+ pkgPath,
45
+ version,
46
+ };
47
+ return memo;
74
48
  });
75
- // antd import
76
- // TODO: use api.modifyConfig for support with vite
77
- api.chainWebpack((memo) => {
78
- function getUserLibDir({ library }) {
79
- if (
80
- // @ts-ignore
81
- (api.pkg.dependencies && api.pkg.dependencies[library]) ||
82
- // @ts-ignore
83
- (api.pkg.devDependencies && api.pkg.devDependencies[library]) ||
84
- // egg project using `clientDependencies` in ali tnpm
85
- // @ts-ignore
86
- (api.pkg.clientDependencies && api.pkg.clientDependencies[library])) {
87
- return (0, utils_1.winPath)((0, path_1.dirname)(
88
- // 通过 resolve 往上找,可支持 lerna 仓库
89
- // lerna 仓库如果用 yarn workspace 的依赖不一定在 node_modules,可能被提到根目录,并且没有 link
90
- utils_1.resolve.sync(`${library}/package.json`, {
91
- basedir: api.paths.cwd,
92
- })));
93
- }
94
- return null;
49
+ api.modifyConfig((memo) => {
50
+ checkPkgPath();
51
+ // antd import
52
+ memo.alias.antd = pkgPath;
53
+ // moment > dayjs
54
+ if (memo.antd.dayjs) {
55
+ memo.alias.moment = (0, path_1.dirname)(require.resolve('dayjs/package.json'));
95
56
  }
96
- memo.resolve.alias.set('antd', getUserLibDir({ library: 'antd' }) ||
97
- (0, path_1.dirname)(require.resolve('antd/package.json')));
98
- if (dayjs !== false) {
99
- const { replaceMoment } = getConfig(api);
100
- if (replaceMoment) {
101
- memo.resolve.alias.set('moment', getUserLibDir({ library: 'dayjs' }) ||
102
- (0, path_1.dirname)(require.resolve('dayjs/package.json')));
103
- }
57
+ // dark mode & compact mode
58
+ if (memo.antd.dark || memo.antd.compact) {
59
+ const { getThemeVariables } = require('antd/dist/theme');
60
+ memo.theme = Object.assign(Object.assign({}, getThemeVariables(memo.antd)), memo.theme);
104
61
  }
105
62
  return memo;
106
63
  });
107
- // dark mode
108
- // compat mode
109
- if ((opts === null || opts === void 0 ? void 0 : opts.dark) || (opts === null || opts === void 0 ? void 0 : opts.compact)) {
110
- // support dark mode, user use antd 4 by default
111
- const { getThemeVariables } = require('antd/dist/theme');
112
- api.modifyDefaultConfig((config) => {
113
- config.theme = Object.assign(Object.assign({}, getThemeVariables(opts)), config.theme);
114
- return config;
115
- });
116
- }
117
- if (dayjs !== false) {
118
- api.onGenerateFiles({
119
- fn: () => {
120
- const { plugins } = getConfig(api);
121
- const runtimeTpl = (0, fs_1.readFileSync)((0, path_1.join)(__dirname, '../templates/antd/dayjs.tpl'), 'utf-8');
122
- api.writeTmpFile({
123
- path: 'plugin-antd/dayjs.tsx',
124
- content: utils_1.Mustache.render(runtimeTpl, {
125
- plugins,
126
- dayjsPath: (0, path_1.dirname)(require.resolve('dayjs/package.json')),
127
- dayjsPluginPath: (0, path_1.dirname)(require.resolve('antd-dayjs-webpack-plugin/package.json')),
128
- }),
129
- });
130
- },
131
- });
132
- api.addEntryCodeAhead(() => {
133
- return [`import './${DIR_NAME}/dayjs.tsx'`];
134
- });
135
- }
136
64
  // babel-plugin-import
137
65
  api.addExtraBabelPlugins(() => {
138
- return [
139
- [
140
- require.resolve('babel-plugin-import'),
141
- {
142
- libraryName: 'antd',
143
- libraryDirectory: 'es',
144
- style: true,
145
- },
146
- ],
147
- ];
66
+ const style = api.config.antd.style || 'less';
67
+ return api.config.antd.import && !api.appData.vite
68
+ ? [
69
+ [
70
+ require.resolve('babel-plugin-import'),
71
+ {
72
+ libraryName: 'antd',
73
+ libraryDirectory: 'es',
74
+ style: style === 'less' ? true : 'css',
75
+ },
76
+ ],
77
+ ]
78
+ : [];
148
79
  });
149
80
  // antd config provider
150
- // TODO: use umi provider
151
- if (opts === null || opts === void 0 ? void 0 : opts.config) {
152
- api.onGenerateFiles({
153
- fn() {
154
- // runtime.tsx
155
- const runtimeTpl = (0, fs_1.readFileSync)((0, path_1.join)(__dirname, '../templates/antd/runtime.tpl'), 'utf-8');
156
- api.writeTmpFile({
157
- path: `${DIR_NAME}/runtime.tsx`,
158
- content: utils_1.Mustache.render(runtimeTpl, {
159
- config: JSON.stringify(opts === null || opts === void 0 ? void 0 : opts.config),
160
- }),
161
- });
162
- },
81
+ api.onGenerateFiles(() => {
82
+ if (!api.config.antd.configProvider)
83
+ return;
84
+ api.writeTmpFile({
85
+ path: `runtime.tsx`,
86
+ content: plugin_utils_1.Mustache.render(`
87
+ import { ConfigProvider, Modal, message, notification } from 'antd';
88
+
89
+ export function rootContainer(container) {
90
+ const finalConfig = {...{{{ config }}}}
91
+ if (finalConfig.prefixCls) {
92
+ Modal.config({
93
+ rootPrefixCls: finalConfig.prefixCls
94
+ });
95
+ message.config({
96
+ prefixCls: \`\${finalConfig.prefixCls}-message\`
97
+ });
98
+ notification.config({
99
+ prefixCls: \`\${finalConfig.prefixCls}-notification\`
100
+ });
101
+ }
102
+ return <ConfigProvider {...finalConfig}>{container}</ConfigProvider>;
103
+ }
104
+ `.trim(), {
105
+ config: JSON.stringify(api.config.antd.configProvider),
106
+ }),
163
107
  });
164
- //TODO:Runtime Plugin
165
- api.addRuntimePlugin(() => [
166
- (0, path_1.join)(api.paths.absTmpPath, DIR_NAME, 'runtime.tsx'),
167
- ]);
168
- }
108
+ });
109
+ api.addRuntimePlugin(() => {
110
+ return api.config.antd.configProvider
111
+ ? [(0, withTmpPath_1.withTmpPath)({ api, path: 'runtime.tsx' })]
112
+ : [];
113
+ });
114
+ // import antd style if antd.import is not configured
115
+ api.addEntryImportsAhead(() => {
116
+ const style = api.config.antd.style || 'less';
117
+ return api.config.antd.import && !api.appData.vite
118
+ ? []
119
+ : [
120
+ {
121
+ source: style === 'less' ? 'antd/dist/antd.less' : 'antd/dist/antd.css',
122
+ },
123
+ ];
124
+ });
169
125
  };
package/dist/dva.d.ts CHANGED
@@ -1,3 +1,6 @@
1
1
  import { IApi } from 'umi';
2
+ import { Model, ModelUtils } from './utils/modelUtils';
2
3
  declare const _default: (api: IApi) => void;
3
4
  export default _default;
5
+ export declare function getModelUtil(api: IApi | null): ModelUtils;
6
+ export declare function getAllModels(api: IApi): Model[];
package/dist/dva.js CHANGED
@@ -1,9 +1,190 @@
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
  Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.getAllModels = exports.getModelUtil = void 0;
27
+ const t = __importStar(require("@umijs/bundler-utils/compiled/babel/types"));
28
+ const path_1 = require("path");
29
+ const plugin_utils_1 = require("umi/plugin-utils");
30
+ const modelUtils_1 = require("./utils/modelUtils");
31
+ const withTmpPath_1 = require("./utils/withTmpPath");
32
+ const utils_1 = require("@umijs/utils");
3
33
  exports.default = (api) => {
4
- api;
5
- // import from dva
6
- // model register
7
- // container
34
+ const pkgPath = (0, path_1.join)(__dirname, '../libs/dva.ts');
35
+ api.describe({
36
+ config: {
37
+ schema(Joi) {
38
+ return Joi.object({
39
+ extraModels: Joi.array().items(Joi.string()),
40
+ immer: Joi.object(),
41
+ });
42
+ },
43
+ },
44
+ enableBy: api.EnableBy.config,
45
+ });
46
+ api.modifyAppData((memo) => {
47
+ const models = getAllModels(api);
48
+ memo.pluginDva = {
49
+ pkgPath,
50
+ models,
51
+ };
52
+ return memo;
53
+ });
54
+ api.modifyConfig((memo) => {
55
+ // import from dva
56
+ memo.alias['dva$'] = pkgPath;
57
+ return memo;
58
+ });
59
+ api.onGenerateFiles((args) => {
60
+ var _a, _b, _c, _d, _e, _f;
61
+ const models = args.isFirstTime
62
+ ? api.appData.pluginDva.models
63
+ : getAllModels(api);
64
+ // models.ts
65
+ api.writeTmpFile({
66
+ path: 'models.ts',
67
+ content: modelUtils_1.ModelUtils.getModelsContent(models),
68
+ });
69
+ // dva.tsx
70
+ api.writeTmpFile({
71
+ path: 'dva.tsx',
72
+ tpl: `
73
+ // It's faked dva
74
+ // aliased to @umijs/plugins/templates/dva
75
+ import { create, Provider } from 'dva';
76
+ import createLoading from '${(0, utils_1.winPath)(require.resolve('dva-loading'))}';
77
+ ${((_a = api.config.dva) === null || _a === void 0 ? void 0 : _a.immer)
78
+ ? `
79
+ import dvaImmer, { enableES5, enableAllPlugins } from '${(0, utils_1.winPath)(require.resolve('dva-immer'))}';
80
+ `
81
+ : ''}
82
+ import React, { useRef } from 'react';
83
+ import { history } from 'umi';
84
+ import { models } from './models';
85
+
86
+ export function RootContainer(props: any) {
87
+ const app = useRef<any>();
88
+ if (!app.current) {
89
+ app.current = create(
90
+ {
91
+ history,
92
+ },
93
+ {
94
+ initialReducer: {},
95
+ setupMiddlewares(middlewares: Function[]) {
96
+ return [...middlewares];
97
+ },
98
+ setupApp(app: IDvaApp) {
99
+ app._history = history;
100
+ },
101
+ },
102
+ );
103
+ app.current.use(createLoading());
104
+ ${((_b = api.config.dva) === null || _b === void 0 ? void 0 : _b.immer) ? `app.current.use(dvaImmer());` : ''}
105
+ ${((_d = (_c = api.config.dva) === null || _c === void 0 ? void 0 : _c.immer) === null || _d === void 0 ? void 0 : _d.enableES5) ? `enableES5();` : ''}
106
+ ${((_f = (_e = api.config.dva) === null || _e === void 0 ? void 0 : _e.immer) === null || _f === void 0 ? void 0 : _f.enableAllPlugins) ? `enableAllPlugins();` : ''}
107
+ for (const id of Object.keys(models)) {
108
+ app.current.model(models[id].model);
109
+ }
110
+ app.current.start();
111
+ }
112
+ return <Provider store={app.current!._store}>{props.children}</Provider>;
113
+ }
114
+ `,
115
+ context: {},
116
+ });
117
+ // runtime.tsx
118
+ api.writeTmpFile({
119
+ path: 'runtime.tsx',
120
+ content: `
121
+ import React from 'react';
122
+ import { RootContainer } from './dva';
123
+
124
+ export function dataflowProvider(container, opts) {
125
+ return React.createElement(RootContainer, opts, container);
126
+ }
127
+ `,
128
+ });
129
+ // index.ts for export
130
+ api.writeTmpFile({
131
+ path: 'index.ts',
132
+ content: `
133
+ export { connect, useDispatch, useStore, useSelector } from 'dva';`,
134
+ });
135
+ });
136
+ api.addTmpGenerateWatcherPaths(() => {
137
+ return [(0, path_1.join)(api.paths.absSrcPath, 'models')];
138
+ });
139
+ api.addRuntimePlugin(() => {
140
+ return [(0, withTmpPath_1.withTmpPath)({ api, path: 'runtime.tsx' })];
141
+ });
8
142
  // dva list model
143
+ api.registerCommand({
144
+ name: 'dva',
145
+ fn() {
146
+ api.logger.info(plugin_utils_1.chalk.green.bold('dva models'));
147
+ api.appData.pluginDva.models.forEach((model) => {
148
+ api.logger.info(` - ${(0, path_1.relative)(api.cwd, model.file)}`);
149
+ });
150
+ },
151
+ });
9
152
  };
153
+ function getModelUtil(api) {
154
+ return new modelUtils_1.ModelUtils(api, {
155
+ contentTest(content) {
156
+ return content.startsWith('// @dva-model');
157
+ },
158
+ astTest({ node, content }) {
159
+ if (isModelObject(node)) {
160
+ return true;
161
+ }
162
+ else if (content.includes('dva-model-extend') &&
163
+ t.isCallExpression(node) &&
164
+ node.arguments.length === 2 &&
165
+ isModelObject(node.arguments[1])) {
166
+ return true;
167
+ }
168
+ return false;
169
+ },
170
+ });
171
+ }
172
+ exports.getModelUtil = getModelUtil;
173
+ function getAllModels(api) {
174
+ return getModelUtil(api).getAllModels({
175
+ extraModels: [...(api.config.dva.extraModels || [])],
176
+ });
177
+ }
178
+ exports.getAllModels = getAllModels;
179
+ function isModelObject(node) {
180
+ return (t.isObjectExpression(node) &&
181
+ node.properties.some((property) => {
182
+ return [
183
+ 'state',
184
+ 'reducers',
185
+ 'subscriptions',
186
+ 'effects',
187
+ 'namespace',
188
+ ].includes(property.key.name);
189
+ }));
190
+ }