index.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * qiankun配置
  3. */
  4. import { loadMicroApp } from 'qiankun';
  5. import { apps } from './apps';
  6. import { getProps } from './state';
  7. const activeApps = {};
  8. /**
  9. * 重构apps
  10. */
  11. function filterApps() {
  12. apps.forEach((item) => {
  13. //主应用需要传递给微应用的数据。
  14. item['props'] = getProps();
  15. console.log('主应用给子应用传的数据', item.props);
  16. //微应用触发的路由规则
  17. // @ts-ignore
  18. item.activeRule = item.activeRule.startsWith('/') ? item.activeRule : `/${item.activeRule}`;
  19. });
  20. return apps;
  21. }
  22. const mountMicroApp = (path, toPath?) => {
  23. const microApps = filterApps();
  24. const app = microApps.find((item) => path.startsWith(item['activeRule']));
  25. if (app) {
  26. if (activeApps[app['activeRule']]) {
  27. // return;
  28. activeApps[app['activeRule']].unmount();
  29. activeApps[app['activeRule']] = null;
  30. delete activeApps[app['activeRule']];
  31. }
  32. const instance = activeApps[app['activeRule']];
  33. console.log('子应用实例--------------->', instance);
  34. if (instance) {
  35. instance.update();
  36. } else {
  37. if (toPath) {
  38. app['props']['data']['publicPath'] = toPath;
  39. }
  40. activeApps[app['activeRule']] = loadMicroApp(app, {
  41. fetch(url, ...args) {
  42. // 给指定的微应用 entry 开启跨域请求
  43. if (url === 'http://1.1.1.3:89/cookie/flash.js') {
  44. return window.fetch(url, {
  45. ...args,
  46. headers: {
  47. 'Access-Control-Allow-Origin': '*',
  48. },
  49. mode: 'cors',
  50. credentials: 'include',
  51. });
  52. }
  53. return window.fetch(url, ...args);
  54. },
  55. }); // 手动加载子应用
  56. }
  57. }
  58. };
  59. // 卸载app的方法
  60. const unmountMicroApps = (multipleApp) => {
  61. if (JSON.stringify(activeApps) !== '{}' && multipleApp.some) {
  62. for (const key in activeApps) {
  63. const isExist = multipleApp.some((name) => name == key);
  64. if (isExist) {
  65. activeApps[key].unmount();
  66. activeApps[key] = null;
  67. delete activeApps[key];
  68. }
  69. }
  70. }
  71. };
  72. export { mountMicroApp, unmountMicroApps, activeApps };