要将现有的前端工程改造成微前端,不会太难。如果是 Vue 开发的,搭配 Engage FE CLI 工具改造则更加简单。下面以 Vue 前端工程为例:
- package.json 中引入最新版本的 @engage/fe-cli 依赖(该包位于国双 npm registry 中),增加若干 scripts,移除 vue、vue-router、vuex 等依赖(因为在浏览器内运行时平台已经包含这些依赖了):
"scripts": {
"lint": "devsak-lint && engage-fe-cli-stylelint",
"dev": "engage-fe-cli-webpack-dev",
"build": "engage-fe-cli-webpack-build",
"prepush": "npm run lint"
},
"devDependencies": {
"@engage/fe-cli": "1.1.49"
},
- src/main.js(webpack entry)中改造如下:
import App from '@/App.vue';
import router from '@/router';
import { createMfeApp } from 'engage';
import '@/assets/css/index.scss'; // 如果有 css 等样式,可以引入
export const mfeApp = createMfeApp({
component: App, router,
});
- src/App.vue 文件中 id 由 app 改为 mfe-app,即:
<template>
<div id="mfe-app">
<router-view />
</div>
</template>
- index.html 修改如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample App</title>
<script lang="javascript">
// 本地开发时使用的配置
var _ENGAGE_COMMON_CONFIG = {
mfeApps: {
'mfe-sample-app': {
pages: ["/sample-app"],
navs: [ // 导航
{name: "Sample App Home", entry: "/sample-app"},
]
}
}
};
</script>
<!-- 引入 Engage 开发库 -->
<!-- 集成环境:https://alpha-engage.gridsumdissector.com/platform/load-latest-engage-common.js
测试环境:https://beta-engage.gridsumdissector.com/platform/load-latest-engage-common.js
UAT环境:https://uat-engage.gridsumdissector.com/platform/load-latest-engage-common.js
正式环境:https://app.engage-all.com/platform/load-latest-engage-common.js -->
<script src="https://alpha-engage.gridsumdissector.com/platform/load-latest-engage-common.js"></script>
</head>
<body>
<!-- id 必须固定为 mfe-anchor -->
<div id="mfe-anchor" />
</body>
</html>