vue2 為主應用 react 為子應用
在項目中安裝乾坤
yarn add qiankun # 或者 npm i qiankun -S
vue主應用
在main.js中新增 (需要注意的是路由模型為history模式)
registerMicroApps([{name: 'reactApp',entry: '//localhost:3011',container: '#container',//主應用掛在子應用的容器id名稱activeRule: '/app-react',//主應用掛在子應用的路由名稱},{name: 'vueApp',entry: '//localhost:8080',container: '#container',activeRule: '/app-vue',},
]);
react 子應用:
修改 index.js文件
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { HashRouter } from 'react-router-dom';
function render(props) {const { container } = props;// console.log('====================================');console.log(container);console.log('====================================');// container 存在 說明是作為子應用運行 不存在則是獨立運行const root = ReactDOM.createRoot(container ? container.querySelector('#appRoot') : document.getElementById('appRoot'));//需要注意的是 appRoot 和 public目錄下index.html 中div的id名稱保持一致root.render(<HashRouter ><App /></HashRouter>
);
}// 如果是獨立運行
if (!window.__POWERED_BY_QIANKUN__) {render({});
}export async function bootstrap() {console.log('react app bootstraped');
}export async function mount(props) {console.log('react app mounted', props);render(props);
}export async function unmount(props) {const { container } = props;const root = ReactDOM.createRoot(container ? container.querySelector('#root') : document.getElementById('root'));root.unmount();
}
修改webpack配置,安裝craco
yarn add react-app-rewired 或 npm i -D react-app-rewired
根目錄下新增 config-overrides.js
文件
const { name } = require('./package');module.exports = {webpack: (config) => {config.output.library = `${name}-[name]`;config.output.libraryTarget = 'umd';// config.output.jsonpFunction = `webpackJsonp_${name}`;config.output.globalObject = 'window';return config;},devServer: (_) => {const config = _;config.headers = {'Access-Control-Allow-Origin': '*',};config.historyApiFallback = true;config.hot = false;config.watchContentBase = false;config.liveReload = false;return config;},
};
修改package.json
文件
這里端口號需要和子應用掛在的端口號保持一致
如在主應用在掛在子應用時遇到
需要再子應用 package.json 中 eslintConfig 中新增
[外鏈圖片轉存中…(img-5Wnjp92F-1748775941845)]
需要再子應用 package.json 中 eslintConfig 中新增
[外鏈圖片轉存中…(img-YZw30X77-1748775941845)]
參考鏈接 React 18 配置 QianKun:主應用【React 18】+ 微應用【React 18】前端技能提升 react - 掘金