无界作为新一代微前端框架,提供了丰富的配置选项来满足不同场景需求。下面我将分类详解所有核心配置项,并附上实用示例:
一、容器配置(主应用)
1. 基础配置
javascript
<WujieVue
name="subApp" // 【必需】子应用唯一标识
url="http://localhost:3000" // 【必需】子应用入口URL
width="100%" // 容器宽度
height="800px" // 容器高度
:alive="true" // 是否保活(切换时不销毁)
:replace="false" // 是否替换当前路由
:sync="true" // 是否同步路由
:fetch="customFetch" // 自定义fetch方法
:props="{ user: currentUser }" // 传递给子应用的数据
:degrade="false" // 是否降级到iframe模式
:loading="loadingComponent" // 自定义loading组件
:preload="true" // 是否预加载
/>
2. 沙箱配置
javascript
<WujieVue
:sandbox="{
css: true, // 开启CSS隔离(默认true)
js: true, // 开启JS隔离(默认true)
event: false, // 是否隔离事件(默认false)
strict: false, // 严格沙箱模式(默认false)
exclude: [/jquery/] // 排除沙箱的全局变量
}"
/>
3. 资源加载配置
javascript
<WujieVue
:excludeAssetFilter={(url) =>
url.includes('reset.css') || // 排除特定CSS
url.endsWith('.map') // 排除sourcemap
}
:execQueueMax="5" // 最大并行加载数
:resourceCache="true" // 启用资源缓存
/>
二、子应用配置
1. 入口文件改造
javascript
// react子应用入口(index.js)
if (window.__POWERED_BY_WUJIE__) {
let instance;
// 挂载生命周期
window.__WUJIE_MOUNT = () => {
instance = ReactDOM.render(
<App />,
document.getElementById('root')
);
};
// 卸载生命周期
window.__WUJIE_UNMOUNT = () => {
ReactDOM.unmountComponentAtNode(
document.getElementById('root')
);
};
// 保活模式下的生命周期
window.__WUJIE_HIDE = () => {
document.getElementById('root').style.visibility = 'hidden';
};
window.__WUJIE_SHOW = () => {
document.getElementById('root').style.visibility = 'visible';
};
} else {
ReactDOM.render(<App />, document.getElementById('root'));
}
2. 子应用通信配置
javascript
// 子应用主动通信
export const setupSubApp = () => {
if (!window.$wujie) return;
// 暴露子应用API
window.$wujie.expose({
refreshData: () => store.dispatch('loadData'),
updateTheme: (theme) => setTheme(theme)
});
// 监听主应用事件
window.$wujie.bus.$on('main-event', (payload) => {
console.log('收到主应用消息', payload);
});
};
三、高级配置场景
1. 自定义路由同步方案
javascript
// 主应用配置(Vue Router)
{
path: '/subapp/:path*',
component: WujieVue,
props: (route) => ({
name: 'subApp',
url: process.env.SUB_APP_URL,
sync: false, // 关闭自动同步
props: {
// 手动传递路由参数
routePath: route.path,
routeQuery: route.query
}
})
}
// 子应用内部路由监听
window.$wujie?.bus.$on('sub-route-change', (path) => {
router.push(path);
});
2. 动态资源重写
javascript
// 主应用配置
<WujieVue
:beforeLoad={(appWindow) => {
// 重写CDN路径
appWindow.__rewriteResource = (url) =>
url.replace('//old-cdn.com', '//new-cdn.com');
}}
/>
// 子应用劫持资源加载
const originalCreateElement = document.createElement;
document.createElement = function(tagName, options) {
const el = originalCreateElement.call(this, tagName, options);
if (tagName === 'script' && window.__rewriteResource) {
const _src = Object.getOwnPropertyDescriptor(
HTMLScriptElement.prototype, 'src'
);
Object.defineProperty(el, 'src', {
get: _src.get,
set: (value) => _src.set.call(el, window.__rewriteResource(value))
});
}
return el;
};
四、性能优化配置
1. 智能预加载策略
javascript
// 按需预加载子应用
const preloadMap = {
dashboard: { url: '//app1.com', preload: true },
report: { url: '//app2.com', preload: false }
};
// 路由守卫中触发预加载
router.beforeEach((to) => {
const appName = to.meta.app;
if (preloadMap[appName] && !preloadMap[appName].loaded) {
import('wujie').then(({ preloadApp }) => {
preloadApp({ ...preloadMap[appName] });
preloadMap[appName].loaded = true;
});
}
});
2. 资源缓存配置
javascript
// 自定义带缓存的fetch
const cachedFetch = (url, options) => {
const cacheKey = `wujie:${url}`;
// 从缓存读取
const cached = localStorage.getItem(cacheKey);
if (cached && performance.now() - JSON.parse(cached).timestamp < 600000) {
return Promise.resolve(
new Response(new Blob([JSON.parse(cached).data]))
);
}
// 实际请求
return fetch(url, options).then(async res => {
const clone = res.clone();
const data = await clone.text();
localStorage.setItem(cacheKey, JSON.stringify({
data,
timestamp: performance.now()
}));
return res;
});
};
<WujieVue :fetch="cachedFetch" />
五、安全隔离配置
1. 严格沙箱模式
javascript
<WujieVue
:sandbox="{
strict: true, // 启用严格模式
exclude: [ // 允许访问的安全全局变量
'safeGlobal',
/^Security/
]
}"
:beforeLoad={(appWindow) => {
// 删除危险API
delete appWindow.eval;
delete appWindow.WebAssembly;
// 重写敏感方法
appWindow.localStorage.setItem = (key, value) => {
if (!key.startsWith('app1_')) {
throw new Error('Invalid storage key');
}
Storage.prototype.setItem.call(localStorage, key, value);
};
}}
/>
六、错误处理配置
1. 全局错误捕获
javascript
<WujieVue
:onError={(error) => {
// 分类处理错误
switch(error.type) {
case 'script':
sentry.captureException(error);
return <ScriptErrorPage />;
case 'timeout':
return <TimeoutPage retry={error.retry} />;
default:
return <ErrorPage code="500" />;
}
}}
:timeout="30000" // 加载超时时间(毫秒)
:retryLimit="3" // 最大重试次数
:retryInterval="2000" // 重试间隔
/>
七、调试配置
1. 开发模式增强
javascript
// 主应用配置
<WujieVue
:plugins={[
{
// 开发工具插件
install(app, options) {
if (process.env.NODE_ENV === 'development') {
app.config.devtools = true;
// 注入调试工具
const devtools = document.createElement('script');
devtools.src = '/wujie-devtools.js';
document.head.appendChild(devtools);
}
}
}
]}
/>
// 启动调试模式(URL参数)
http://mainapp.com?wujie-debug=true
配置最佳实践总结
- 生产环境推荐配置:
javascript
<WujieVue
name="prodApp"
url="https://cdn.example.com/app1"
:alive="true"
:sandbox="{ strict: true }"
:excludeAssetFilter={url => url.includes('monitor.js')}
:props="{ token: getAuthToken() }"
:timeout="15000"
:preload="true"
:resourceCache="true"
/>
- 开发环境推荐配置:
javascript
<WujieVue
name="devApp"
url="http://localhost:3001"
:sync="true"
:plugins={[devtoolsPlugin]}
:onError={devErrorHandler}
:beforeLoad={window => (window.__DEV__ = true)}
:degrade={!window.WebComponents}
/>
关键配置选择指南:
- 隔离需求高 → 启用
strict
沙箱模式- 性能敏感 → 开启
preload
+resourceCache
- 第三方接入 → 使用
excludeAssetFilter
排除全局样式- 安全要求高 → 配置
beforeLoad
沙箱加固- 复杂通信 → 结合
props
+bus
+sharedStore
通过合理组合这些配置项,您可以根据具体场景构建出安全、高效、易维护的微前端架构。无界的强大之处在于其配置的灵活性,建议根据实际需求逐步优化配置方案。