1 | import { IApi } from 'umi-types';
|
2 | import { isPlainObject, isEqual } from 'lodash';
|
3 | import ui from './ui';
|
4 |
|
5 | function toObject(o) {
|
6 | if (!isPlainObject(o)) {
|
7 | return {};
|
8 | } else {
|
9 | return o;
|
10 | }
|
11 | }
|
12 |
|
13 | function getId(id) {
|
14 | return `umi-plugin-react:${id}`;
|
15 | }
|
16 |
|
17 | function getPlugins(obj) {
|
18 | return Object.keys(obj).filter(key => obj[key]);
|
19 | }
|
20 |
|
21 | function diffPlugins(newOption, oldOption) {
|
22 | return Object.keys(newOption).filter(key => {
|
23 | return newOption[key] && !isEqual(newOption[key], oldOption[key]);
|
24 | });
|
25 | }
|
26 |
|
27 | export default function(api: IApi, option) {
|
28 | const { debug } = api;
|
29 |
|
30 | api.onOptionChange(newOption => {
|
31 | debug('new option');
|
32 | debug(newOption);
|
33 | if (isEqual(getPlugins(newOption), getPlugins(option))) {
|
34 | diffPlugins(newOption, option).forEach(key => {
|
35 | debug(`change plugin option: ${key}`);
|
36 | api.changePluginOption(getId(key), newOption[key]);
|
37 | });
|
38 | option = newOption;
|
39 | } else {
|
40 | debug('restart');
|
41 | api.restart();
|
42 | }
|
43 | });
|
44 |
|
45 | const plugins = {
|
46 |
|
47 | hd: () => require('./plugins/hd').default,
|
48 | fastClick: () => require('./plugins/fastClick').default,
|
49 |
|
50 |
|
51 | library: () => require('./plugins/library').default,
|
52 | dynamicImport: () => require('./plugins/dynamicImport').default,
|
53 | dll: () => require('./plugins/dll').default,
|
54 | hardSource: () => require('./plugins/hardSource').default,
|
55 | pwa: () => require('./plugins/pwa').default,
|
56 |
|
57 |
|
58 | chunks: () => require('./plugins/chunks').default,
|
59 | scripts: () => require('./plugins/scripts').default,
|
60 | headScripts: () => require('./plugins/headScripts').default,
|
61 | links: () => require('./plugins/links').default,
|
62 | metas: () => require('./plugins/metas').default,
|
63 |
|
64 |
|
65 | dva: () => require('./plugins/dva').default,
|
66 | locale: () => require('./plugins/locale').default,
|
67 | polyfills: () => require('./plugins/polyfills').default,
|
68 | routes: () => require('./plugins/routes').default,
|
69 | antd: () => require('./plugins/antd').default,
|
70 | title: () => require('./plugins/title').default,
|
71 | };
|
72 |
|
73 | Object.keys(plugins).forEach(key => {
|
74 | if (option[key]) {
|
75 | let opts = option[key];
|
76 | if (key === 'locale') {
|
77 | opts = {
|
78 | antd: option.antd,
|
79 | ...opts,
|
80 | };
|
81 | }
|
82 | if (key === 'dva') {
|
83 | opts = {
|
84 | dynamicImport: option.dynamicImport,
|
85 | ...toObject(opts),
|
86 | };
|
87 | }
|
88 |
|
89 | api.registerPlugin({
|
90 | id: getId(key),
|
91 | apply: plugins[key](),
|
92 | opts,
|
93 | });
|
94 | }
|
95 | });
|
96 |
|
97 |
|
98 | ui(api);
|
99 | }
|