Web组件化 - 原生js实现组件

第一篇介绍了如何将React组件转换为Web Component
第二篇介绍了子应用(Web Component)中的路由可以正常作用与Shell App
第三篇介绍了Sub App与Shell App通过属性或自定义事件交互
第四篇介绍Web Component + React实现微前端的POC
第五篇子应用Webpack排除React依赖包
第六篇子应用的样式隔离
第七篇动态web组件标签
第八篇IE兼容

前几篇文章介绍了用React实现sub app的Web组件化,这次我们再尝试用原生js实现,并用Webpack打包。在Shell App中以同样的方式调用。代码实现如下:

npm init
mkdir src

src/index.js

class HelloElement extends HTMLElement {
  constructor () {
      super();
  }

  connectedCallback() {
    const shadowEle = this.attachShadow({ mode: 'open' });
    shadowEle.innerHTML = `
      <p>Hello from Web Component!</p>
    `;     
  }
}

const tagName = "x-component";

if (!window.customElements.get(tagName)) {
  window.customElements.define(tagName, HelloElement);
}

package.json

{
  "name": "sample-1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^5.1.2",
    "style-loader": "^2.0.0",
    "webpack": "^5.25.0",
    "webpack-cli": "^4.5.0"
  },
  "dependencies": {
    "express": "^4.17.1"
  }
}

server.js

const path = require('path');
const express = require('express')
const app = express()
const port = 5003
const fileRoot = path.resolve(__dirname, './dist');

app.use(express.static(path.join(__dirname, './dist')))

app.get('/', (req, res) => {
    res.sendFile('index.bundle.js', { root: fileRoot });
})

app.get('/bundle', (req, res) => {
    res.sendFile('index.bundle.js', { root: fileRoot });
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'index.bundle.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      }
    ],
  },
};

执行
npm run build
node server.js

该sub app会发布在5003端口。修改shell app -> app.js,增加上述sub app的调用即可。
最后附上源码地址

不论React还是原生代码写的Web Component,其原理都是相同的,即将Web组件打包后发布在某个url,供Shell App加载。由于Web Component天生的代码、样式隔离,非常适合微前端。

posted @ 2021-11-04 21:50  老胡Andy  阅读(580)  评论(0编辑  收藏  举报