1、创建一个没有初始应用程序的空微服务载体microServiceParent
ng new --create-application=false microServiceParent
cd microServiceParent
2、新增一个应用程序microServiceParent 带路由 (以下简称parent)
ng g application microServiceParent --routing --style=css
3、新增一个应用程序microServiceChild 不带路由(以下简称child)
ng g application microServiceChild --routing=false --style=css
4、加入一个angular 的一个内建功能
ng add @angular/elements --project=microServiceChild
5、加入一个套件ngx-build-plus,可以把build出来的文件自动合并
ng add ngx-build-plus --project=microServiceChild
6、安装angular-extensions/elements 套件
npm i @angular-extensions/elements
正式开始:
1、(child)移除app.component的selector属性
2、(child)移除app.module的bootstrap属性
3、(child)app.module中新增
4、(child)目录下进行一次编译
ng build --project=microServiceChild --configuration production --output-hashing=none --single-bundle
编译过后可以看到dist目录下的main.js,将这个文件载入到任意网页就能直接运行ng应用
5、(parent)app.modules中引入并import,然后添加schemas,注意需要从@angular/core引入
6、(parent)在app.component.ts中写入
elementUrl = '/micro-service-child.js'
7、(parent)清空app.component.html的内容(只是方便演示)
写入元素:
<micro-service-child *axLazyElement="elementUrl"></micro-service-child>
使用刚刚引入的结构性指令懒加载js
8、(parent)编译
ng build --project=microServiceParent --configuration production --output-hashing=none
9、把child的主进程main.js和兼容性文件polyfill.js复制到parent目录下
注意main.js更名时需要与tag的名字相同!!!我这里是micro-service-child,
10、启动编译后的程序
可以看到自定义微前端已载入!
一些备注
- 启动项目
lite-server
这里使用轻量级server进行测试
npm install lite-server -g
- 编译项目
--output-hashing 定义输出文件名的缓存无效哈希(cache-busting hashing)的模式。
--prod 在V14版本已移除 改用 --configuration production
捆绑文件
最小化多余的空格
删除注释和死代码
重写代码以使用残缺的短名称(缩小)
--single-bundle 构建出的js会合并为一支,这样子可以方便自订元素
microServiceParent microServiceChild 说明
- 关于Polyfills(兼容性)的设定
使用于非angular网页环境需要额外载入zone.js才能执行
node_modules\zone.js\dist\zone.min.js
如果是angular项目,一般不额外引入Polyfills
可以先在package.json中编写一个脚本命令build:microServiceChild:deploy
这个脚本的思路很简单,就是把child的主进程main.js和兼容性文件polyfill.js复制到parent目录下
"build:microServiceChild:deploy":"copy dist/micro-service-child/main.js dist/micro-service-parent/micro-service-child.js && copy dist/micro-service-child/polyfills.js dist/micro-service-parent/child-polyfills.js"
然后使用命令:
npm run-script build:microServiceChild:deploy