前后端不分离项目导入react模块

前言

  • 我最近在整一个前后端不分离使用.net写的项目。这种前后端不分离的都是有类似的模板渲染。我们肯定不继续写.net了,所以需要自己的react组件导入进来。
  • 本来我一开始想着react打包umd进行引入,使用tsdx配合http-server就可以进行开发了,但是后来觉得不是太好,如果项目越来越大,那么这个umd包就越来越大。所以最好使用多入口打包成mpa方式自己修改打包配置,或者使用现成的东西。
  • 然后我就发现可以使用icestark的微模块进行引入。脚手架里多入口打包已经配好了。

官网

  • https://micro-frontends.ice.work/docs/guide/micro-module#api
  • 注意,这个微模块我发现有点小bug,但不影响正常显示。

改造流程

  • 首先利用它给的脚手架创建项目:
# 创建文件夹
$ mkdir micro-module & cd micro-module

# 初始化
$ iceworks init component @icedesign/template-icestark-module

# 安装依赖
$ npm install
$ npm start
  • 然后你需要配置你的入口地址:
// build.json
{
    
    
  "plugins": [
    ["build-plugin-stark-module", {
    
    
      "modules": {
    
    
        "branch-detail": "./src/branch-detail/index.tsx",
        "edit-info": "./src/edit-info/index.tsx"
      }
    }]
  ]
}
  • 写对应的react组件。
  • 在原生js中,由于没有jsx,所以我们需要在html上一开始就导入react,react-dom,以及用于渲染的micromodule。
  • micromodule可以单独配置成一个入口,一开始就加载它,每个modules入口都是一个umd,icestark会额外给这个导出对象添加mount与unmount方法。
  • 配置micromodule入口
"build-plugin-stark-module",
			{
    
    
			  ...
				"modules": {
    
    
					"globalmodule": "./src/globalmodule/index.tsx",
  • micromodule直接导出即可:
import {
    
     MicroModule } from "@ice/stark-module";

export {
    
     MicroModule };
  • 如果需要配置external :
// build.json
"build-plugin-stark-module",
			{
    
    
			 ...
				"moduleExternals": {
    
    
					"react": {
    
    
						"root": "React",
						"url": "https://g.alicdn.com/code/lib/react/16.14.0/umd/react.production.min.js"
					},
					"react-dom": {
    
    
						"root": "ReactDOM",
						"url": "https://g.alicdn.com/code/lib/react-dom/16.14.0/umd/react-dom.production.min.js"
					},
			}
  • 我们在html上由于预先加载了micromodule的umd,所以可以从window上拿到它:
	const MicroModule = window["yourmicromodule"].MicroModule;
		const moduleInfo = {
    
    
			name: "moduleA",
			url: [
				"http://localhost:8080/build/moduleA/index.js",
				"http://localhost:8080/build/moduleA/index.css",
			],
			runtime: "http://localhost:8080/build/moduleA/runtime.json",
		};
  • 然后获取id的dom使用react-dom进行渲染即可:
			ReactDOM.render(
				React.createElement(MicroModule, {
    
     moduleInfo }),
				document.getElementById("myroot")
			);
  • 如果需要卸载:
ReactDOM.unmountComponentAtNode(document.getElementById("myroot"));

猜你喜欢

转载自blog.csdn.net/yehuozhili/article/details/129831044