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

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/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,11 +1,113 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const path_1 = require("path");
4
+ const plugin_utils_1 = require("umi/plugin-utils");
5
+ const resolveProjectDep_1 = require("./utils/resolveProjectDep");
6
+ const withTmpPath_1 = require("./utils/withTmpPath");
3
7
  exports.default = (api) => {
4
- api;
5
- // antd import
6
- // dark mode
7
- // compat mode
8
- // dayjs (by default?)
8
+ const pkgPath = (0, resolveProjectDep_1.resolveProjectDep)({
9
+ pkg: api.pkg,
10
+ cwd: api.cwd,
11
+ dep: 'antd',
12
+ }) || (0, path_1.dirname)(require.resolve('antd/package.json'));
13
+ api.describe({
14
+ config: {
15
+ schema(Joi) {
16
+ return Joi.object({
17
+ configProvider: Joi.object(),
18
+ // themes
19
+ dark: Joi.boolean(),
20
+ compact: Joi.boolean(),
21
+ // babel-plugin-import
22
+ import: Joi.boolean(),
23
+ // less or css, default less
24
+ style: Joi.string().allow('less', 'css'),
25
+ });
26
+ },
27
+ },
28
+ enableBy: api.EnableBy.config,
29
+ });
30
+ api.modifyAppData((memo) => {
31
+ const version = require(`${pkgPath}/package.json`).version;
32
+ memo.antd = {
33
+ pkgPath,
34
+ version,
35
+ };
36
+ return memo;
37
+ });
38
+ api.modifyConfig((memo) => {
39
+ // antd import
40
+ memo.alias.antd = pkgPath;
41
+ // moment > dayjs
42
+ if (memo.antd.dayjs) {
43
+ memo.alias.moment = (0, path_1.dirname)(require.resolve('dayjs/package.json'));
44
+ }
45
+ // dark mode & compact mode
46
+ if (memo.antd.dark || memo.antd.compact) {
47
+ const { getThemeVariables } = require('antd/dist/theme');
48
+ memo.theme = Object.assign(Object.assign({}, getThemeVariables(memo.antd)), memo.theme);
49
+ }
50
+ return memo;
51
+ });
9
52
  // babel-plugin-import
10
- // antd config provider (HOLD, depends on umi)
53
+ api.addExtraBabelPlugins(() => {
54
+ const style = api.config.antd.style || 'less';
55
+ return api.config.antd.import
56
+ ? [
57
+ [
58
+ require.resolve('babel-plugin-import'),
59
+ {
60
+ libraryName: 'antd',
61
+ libraryDirectory: 'es',
62
+ style: style === 'less' ? true : 'css',
63
+ },
64
+ ],
65
+ ]
66
+ : [];
67
+ });
68
+ // antd config provider
69
+ api.onGenerateFiles(() => {
70
+ if (!api.config.antd.config)
71
+ return;
72
+ api.writeTmpFile({
73
+ path: `runtime.tsx`,
74
+ content: plugin_utils_1.Mustache.render(`
75
+ import { ConfigProvider, Modal, message, notification } from 'antd';
76
+
77
+ export function rootContainer(container) {
78
+ const finalConfig = {...{{{ config }}}}
79
+ if (finalConfig.prefixCls) {
80
+ Modal.config({
81
+ rootPrefixCls: finalConfig.prefixCls
82
+ });
83
+ message.config({
84
+ prefixCls: \`\${finalConfig.prefixCls}-message\`
85
+ });
86
+ notification.config({
87
+ prefixCls: \`\${finalConfig.prefixCls}-notification\`
88
+ });
89
+ }
90
+ return <ConfigProvider {...finalConfig}>{container}</ConfigProvider>;
91
+ }
92
+ `.trim(), {
93
+ config: JSON.stringify(api.config.antd.config),
94
+ }),
95
+ });
96
+ });
97
+ api.addRuntimePlugin(() => {
98
+ return api.config.antd.config
99
+ ? [(0, withTmpPath_1.withTmpPath)({ api, path: 'runtime.tsx' })]
100
+ : [];
101
+ });
102
+ // import antd style if antd.import is not configured
103
+ api.addEntryImportsAhead(() => {
104
+ const style = api.config.antd.style || 'less';
105
+ return api.config.antd.import
106
+ ? []
107
+ : [
108
+ {
109
+ source: style === 'less' ? 'antd/dist/antd.less' : 'antd/dist/antd.css',
110
+ },
111
+ ];
112
+ });
11
113
  };
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,174 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
2
21
  Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.getAllModels = exports.getModelUtil = void 0;
23
+ const t = __importStar(require("@umijs/bundler-utils/compiled/babel/types"));
24
+ const path_1 = require("path");
25
+ const plugin_utils_1 = require("umi/plugin-utils");
26
+ const modelUtils_1 = require("./utils/modelUtils");
27
+ const withTmpPath_1 = require("./utils/withTmpPath");
3
28
  exports.default = (api) => {
4
- api;
5
- // import from dva
6
- // model register
7
- // container
29
+ const pkgPath = (0, path_1.join)(__dirname, '../libs/dva.ts');
30
+ api.describe({
31
+ config: {
32
+ schema(Joi) {
33
+ return Joi.object({
34
+ extraModels: Joi.array().items(Joi.string()),
35
+ });
36
+ },
37
+ },
38
+ enableBy: api.EnableBy.config,
39
+ });
40
+ api.modifyAppData((memo) => {
41
+ const models = getAllModels(api);
42
+ memo.pluginDva = {
43
+ pkgPath,
44
+ models,
45
+ };
46
+ return memo;
47
+ });
48
+ api.modifyConfig((memo) => {
49
+ // import from dva
50
+ memo.alias.dva = pkgPath;
51
+ return memo;
52
+ });
53
+ api.onGenerateFiles((args) => {
54
+ const models = args.isFirstTime
55
+ ? api.appData.pluginDva.models
56
+ : getAllModels(api);
57
+ // models.ts
58
+ api.writeTmpFile({
59
+ path: 'models.ts',
60
+ content: modelUtils_1.ModelUtils.getModelsContent(models),
61
+ });
62
+ // dva.tsx
63
+ api.writeTmpFile({
64
+ path: 'dva.tsx',
65
+ tpl: `
66
+ // It's faked dva
67
+ // aliased to @umijs/plugins/templates/dva
68
+ import { create, Provider } from 'dva';
69
+ import React, { useRef } from 'react';
70
+ import { useAppData } from 'umi';
71
+ import { models } from './models';
72
+
73
+ export function RootContainer(props: any) {
74
+ const { navigator } = useAppData();
75
+ const app = useRef<any>();
76
+ if (!app.current) {
77
+ app.current = create(
78
+ {
79
+ history: navigator,
80
+ },
81
+ {
82
+ initialReducer: {},
83
+ setupMiddlewares(middlewares: Function[]) {
84
+ return [...middlewares];
85
+ },
86
+ setupApp(app: IDvaApp) {
87
+ app._history = navigator;
88
+ },
89
+ },
90
+ );
91
+ for (const id of Object.keys(models)) {
92
+ app.current.model(models[id].model);
93
+ }
94
+ app.current.start();
95
+ }
96
+ return <Provider store={app.current!._store}>{props.children}</Provider>;
97
+ }
98
+ `,
99
+ context: {},
100
+ });
101
+ // runtime.tsx
102
+ api.writeTmpFile({
103
+ path: 'runtime.tsx',
104
+ content: `
105
+ import React from 'react';
106
+ import { RootContainer } from './dva';
107
+
108
+ export function dataflowProvider(container, opts) {
109
+ return React.createElement(RootContainer, opts, container);
110
+ }
111
+ `,
112
+ });
113
+ // index.ts for export
114
+ api.writeTmpFile({
115
+ path: 'index.ts',
116
+ content: `
117
+ export { connect, useDispatch, useStore, useSelector } from 'dva';`,
118
+ });
119
+ });
120
+ api.addTmpGenerateWatcherPaths(() => {
121
+ return [(0, path_1.join)(api.paths.absSrcPath, 'models')];
122
+ });
123
+ api.addRuntimePlugin(() => {
124
+ return [(0, withTmpPath_1.withTmpPath)({ api, path: 'runtime.tsx' })];
125
+ });
8
126
  // dva list model
127
+ api.registerCommand({
128
+ name: 'dva',
129
+ fn() {
130
+ api.logger.info(plugin_utils_1.chalk.green.bold('dva models'));
131
+ api.appData.pluginDva.models.forEach((model) => {
132
+ api.logger.info(` - ${(0, path_1.relative)(api.cwd, model.file)}`);
133
+ });
134
+ },
135
+ });
9
136
  };
137
+ function getModelUtil(api) {
138
+ return new modelUtils_1.ModelUtils(api, {
139
+ contentTest(content) {
140
+ return content.startsWith('// @dva-model');
141
+ },
142
+ astTest({ node, content }) {
143
+ if (isModelObject(node)) {
144
+ return true;
145
+ }
146
+ else if (content.includes('dva-model-extend') &&
147
+ t.isCallExpression(node) &&
148
+ node.arguments.length === 2 &&
149
+ isModelObject(node.arguments[1])) {
150
+ return true;
151
+ }
152
+ return false;
153
+ },
154
+ });
155
+ }
156
+ exports.getModelUtil = getModelUtil;
157
+ function getAllModels(api) {
158
+ return getModelUtil(api).getAllModels({
159
+ extraModels: [...(api.config.dva.extraModels || [])],
160
+ });
161
+ }
162
+ exports.getAllModels = getAllModels;
163
+ function isModelObject(node) {
164
+ return (t.isObjectExpression(node) &&
165
+ node.properties.some((property) => {
166
+ return [
167
+ 'state',
168
+ 'reducers',
169
+ 'subscriptions',
170
+ 'effects',
171
+ 'namespace',
172
+ ].includes(property.key.name);
173
+ }));
174
+ }
@@ -1,5 +1,116 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const withTmpPath_1 = require("./utils/withTmpPath");
3
4
  exports.default = (api) => {
4
- api;
5
+ api.describe({
6
+ config: {
7
+ schema(Joi) {
8
+ return Joi.object({
9
+ loading: Joi.string(),
10
+ });
11
+ },
12
+ },
13
+ enableBy: api.EnableBy.config,
14
+ });
15
+ api.register({
16
+ key: 'addExtraModels',
17
+ fn: () => [(0, withTmpPath_1.withTmpPath)({ api, path: '@@initialState.ts' })],
18
+ });
19
+ api.addRuntimePluginKey(() => ['getInitialState']);
20
+ api.addRuntimePlugin(() => {
21
+ return [(0, withTmpPath_1.withTmpPath)({ api, path: 'runtime.tsx' })];
22
+ });
23
+ api.onGenerateFiles(() => {
24
+ var _a;
25
+ const { loading } = api.config.initialState;
26
+ // Provider.tsx
27
+ api.writeTmpFile({
28
+ path: 'Provider.tsx',
29
+ content: `
30
+ import React from 'react';
31
+ import { useModel } from '@@/plugin-model';
32
+ ${loading
33
+ ? `import Loading from ${loading}`
34
+ : `function Loading() { return <div>loading</div>; }`}
35
+ export default function InitialStateProvider(props: any) {
36
+ const appLoaded = React.useRef(false);
37
+ const { loading = false } = useModel("@@initialState") || {};
38
+ React.useEffect(() => {
39
+ if (!loading) {
40
+ appLoaded.current = true;
41
+ }
42
+ }, [loading]);
43
+ if (loading && !appLoaded.current) {
44
+ return <Loading />;
45
+ }
46
+ return props.children;
47
+ }
48
+ `,
49
+ });
50
+ // @@initialState.ts
51
+ api.writeTmpFile({
52
+ path: '@@initialState.ts',
53
+ content: ((_a = api.appData.appJS) === null || _a === void 0 ? void 0 : _a.exports.includes('getInitialState'))
54
+ ? `
55
+ import { useState, useEffect, useCallback } from 'react';
56
+ import { getInitialState } from '@/app';
57
+
58
+ const initState = {
59
+ initialState: undefined,
60
+ loading: true,
61
+ error: undefined,
62
+ };
63
+
64
+ export default () => {
65
+ const [state, setState] = useState(initState);
66
+ const refresh = useCallback(async () => {
67
+ setState((s) => ({ ...s, loading: true, error: undefined }));
68
+ try {
69
+ const ret = await getInitialState();
70
+ setState((s) => ({ ...s, initialState: ret, loading: false }));
71
+ } catch (e) {
72
+ setState((s) => ({ ...s, error: e, loading: false }));
73
+ }
74
+ // [?]
75
+ // await sleep(10);
76
+ }, []);
77
+
78
+ const setInitialState = useCallback(async (initialState) => {
79
+ setState((s) => {
80
+ if (typeof initialState === 'function') {
81
+ return { ...s, initialState: initialState(s.initialState), loading: false };
82
+ }
83
+ return { ...s, initialState, loading: false };
84
+ });
85
+ // [?]
86
+ // await sleep(10)
87
+ }, []);
88
+
89
+ useEffect(() => {
90
+ refresh();
91
+ }, []);
92
+
93
+ return {
94
+ ...state,
95
+ refresh,
96
+ setInitialState,
97
+ };
98
+ }
99
+ `
100
+ : `
101
+ export default () => ({ loading: false, refresh: () => {} })
102
+ `,
103
+ });
104
+ // runtime.tsx
105
+ api.writeTmpFile({
106
+ path: 'runtime.tsx',
107
+ content: `
108
+ import React from 'react';
109
+ import Provider from './Provider';
110
+ export function innerProvider(container) {
111
+ return <Provider>{ container }</Provider>;
112
+ }
113
+ `,
114
+ });
115
+ });
5
116
  };