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

发布时间:2022-07-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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天生的代码、样式隔离,非常适合微前端。

脚本宝典总结

以上是脚本宝典为你收集整理的Web组件化 - 原生js实现组件全部内容,希望文章能够帮你解决Web组件化 - 原生js实现组件所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: