[Day19] - 打包 Element-UI 的 Vue Component to Web Component

day-15 我们说明了 , 如何将 Vue 的 Component 转换成 Web Component

day-18 说明了 , 如何在 React 专案中 , 引用 Web Component

今天我们来个大翻转吧 !

将 Element-UI 中的元件 , 在 React 中做使用

内文

one 利用 vue-cli 建立一个新专案

$ vue create element-ui-web-component

利用Vue CLI 3 , 建立 Vue 2

建立专案中...

two 安装 element-UI

$ npm i element-ui -S

three 利用 @vue/web-component-wrapper 来包装 web component

// in scr/main.js
import Vue from 'vue'
import 'element-ui/lib/theme-chalk/index.css';
import wrap from '@vue/web-component-wrapper'
import {Button} from 'element-ui';

const CustomElement = wrap(Vue, Button)

window.customElements.define('el-button', CustomElement)

element-UI 的 css 是独立单档 , 因此需要将 element-ui/lib/theme-chalk/index.css 在 web component 中引用

因此我们可以需要建立一个中间 vue 来 extends el-button

并在 style 上引用之

<script>
  import {Button} from "element-ui";

  export default {
    extends: Button,
  };
</script>

<!-- 引用 element-ui 的 css -->
<style scoped src="element-ui/lib/theme-chalk/index.css"/>

只要在 build 的时候 , 加上参数 --enable-shadow-dom false 就可以关闭了 !

之後 引入 element-UI 的 css , 我们就可以得到跟 element-UI 官网相同长相的 el-button

  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">

four 利用 build 指令建立 web component

$ vue-cli-service build --target wc --name el-button ./src/main.js --inline-vue

编译完成後 , 你可以在 dist 资料夹中 , 看到 el-button.js , 那就是产生的 web-component

之後你就可以在 html 中自由使用 <el-button> 了 ~~

five 在 html 中使用建立出来的 el-button

<!-- demo.html -->
<meta charset="utf-8">
<title>el-button demo</title>
<script src="./el-button.js"></script>

<el-button type="warning">警告按钮</el-button>

成果

备注

虽然我们知道如何在 React 专案中使用 Vue Component 不过不建议这样混和使用 , 这样容易提升专案的复杂性

参考资料


<<:  Day-08 你对前端还是後端比较有兴趣?

>>:  Day08 iPhone捷径-分享

Day 14 「不残而废」单元测试、Code Smell 与重构 - Data Class 篇

图片来源:Wikipedia 大家听过「帕拉林匹克运动会(帕奥)」吗?它是自 1960 ~ 70 ...

[Day02 - 规划与设计] 从生活中发想需求

发想自己的需求,看看生活中有什麽是想要改进的或是解决的,再来立定一个主题吧! 目前比较烦恼的大概是:...

Android学习笔记24

今天来用checkbox首先先在xml新增 <CheckBox android:id=&quo...

架构介绍

对於资料、数据分析,已经有一点心得,但多半都停留在断断续续,不够紮实也不够完整,虽然可以弄出一个系统...

Day04 - Docker 简单指令操作

查看服务,进入Container 查看docker启用哪些service $ docker-comp...