实验环境:
- qiankun:
^2.10.16
- next:
14.1.0
- react:
^18.2.0
根据官方手册快速上手教程(链接)
构建主程序实验代码:
qiankun
部分:
// file: micro-base/plugins/qiankun/index.ts
import type { AppMetadata } from 'qiankun';
import { registerMicroApps, start } from "qiankun";
import { Microconfig } from "@/plugins/qiankun/microAppsConfig"
export const QianKunStart = function (){
registerMicroApps(Microconfig);
start();
}
export default QianKunStart;
- 页面引用
// file: micro-base/app/page.tsx
import { useEffect } from "react";
import { QianKunStart } from "@/plugins/qiankun"
export default function Home() {
useEffect(() => {
console.log('QianKunStart...')
QianKunStart();
}, [])
return (
<>
<header>header</header>
<main>
<ul>
<li><a href="/">首页</a></li>
<li><a href="/">子应用</a></li>
</ul>
<div id={'mainView'}></div>
</main>
</>
);
}
运行后出现如下错误提示:
经过几番调试寻找,目前有个来至qiankun issues的解决方案:
- 【在nextjs+react中使用qiankun当作主应用时报错 ReferenceError: window is not defined】
基于这个方案,调整下上面实验代码:
qiankun
部分:
// file: micro-base/plugins/qiankun/index.ts
import type { AppMetadata } from 'qiankun';
// import { registerMicroApps, start } from "qiankun"; // 这段删掉
import { Microconfig } from "@/plugins/qiankun/microAppsConfig"
export const QianKunStart = function (){
// 新增
if(typeof window !== undefined){
// 新增
const { registerMicroApps,start, addGlobalUncaughtErrorHandler } = require('qiankun');
registerMicroApps(Microconfig, lifeCycles);
start();
}
}
export default QianKunStart;
实测可行!