开发一个Vue组件库

其实早在 2018 年的项目中,我就已经开发了 Vue 组件库,在过去的几年里也新写了各种各样的组件库,比如 vue 组件库、react 组件库,包括 taro 组件库。在过去的一年里,我荒废了不少,好在及时反省,也认识到需要对技术保持热情。基于此,从过去收集的书签中进行整理。

创建项目

最早创建 vue 项目是自己手动配置 webpack,后来又使用 vue-cli,现在直接使用

1
npm create vue@latest

然后根据终端提示选择需要的配置就可以了。

编写代码

在编写代码之前 npm install 安装一下依赖。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<template>
<div class="ui-button" @click="emit('click')">
{{ text }}
</div>
</template>
<script setup lang="ts">
defineProps<{
text: string;
}>();

const emit = defineEmits<{
click: [];
}>();
</script>
//
<script lang="ts">
export default {
name: "UiButton",
};
</script>
<style lang="scss">
.ui-button {
border: 1px solid #ccc;
color: red;
}
</style>

这个时候我们就有一个简单组件了,我们在其他的组件中引用就可以使用了。 当然需要外部使用还需要导出

1
2
3
4
5
import UiButton from "./index.vue";
UiButton.install = (app) => {
app.component(UiButton.name, UiButton);
};
export default UiButton;

但是我们使用的时候大多数情况都是全局注册,所以还需要全局导出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import UiButton from "./Button";
const components = [UiButton];

const install = (app) => {
components.forEach((item) => {
app.component(item.name, item);
});
};
const MyUI = {
install,
};

export { UiButton };

export default MyUI;

修改配置

首先需要修改 vite.config.js 文件,对其进行配置修改成库打包的模式,这里输出内容到 lib 文件夹中,配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";

export default defineConfig({
plugins: [vue()],
build: {
outDir: "lib",
lib: {
entry: path.resolve(__dirname, "src/components/index.ts"),
name: "MyUI",
fileName: "my-ui",
},
rollupOptions: {
// 确保外部化处理那些你不想打包进库的依赖
external: ["vue"],
output: {
// 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
globals: {
vue: "Vue",
},
},
},
},
});

发布项目

参考:Npm 包发布实践

[越努力,越幸运!]