如何创建类似于Element UI的Vue 3组件库并上传到npm

755 阅读2分钟

1. 初始化项目

首先,使用Vue CLI来初始化一个新的Vue 3项目。

npm install -g @vue/cli
vue create my-component-library

选择Vue 3并进行相关配置。

2. 设置项目结构

在项目中创建一个components目录,用于存放你的组件。比如:

my-component-library/
├── src/
│   ├── components/
│   │   ├── Button.vue
│   │   ├── Input.vue
│   │   └── ...
│   ├── index.js
│   └── ...
└── package.json

3. 编写组件

src/components目录中编写你的组件。例如,一个简单的按钮组件:

<!-- src/components/Button.vue -->
<template>
  <button class="my-button">
    <slot></slot>
  </button>
</template>

<script>
export default {
  name: 'MyButton'
}
</script>

<style>
.my-button {
  padding: 10px 20px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
.my-button:hover {
  background-color: #358a70;
}
</style>

4. 导出组件

src/index.js中导出所有组件:

// src/index.js
import MyButton from './components/Button.vue'
import MyInput from './components/Input.vue'

const MyComponentLibrary = {
  install(Vue) {
    Vue.component('MyButton', MyButton)
    Vue.component('MyInput', MyInput)
  }
}

export default MyComponentLibrary

// 如果需要按需引入,也可以单独导出
export { MyButton, MyInput }

5. 配置打包

为了发布到npm,需要将你的库打包成可以发布的格式。安装rollup用于打包:

npm install --save-dev rollup rollup-plugin-vue @rollup/plugin-node-resolve @rollup/plugin-commonjs @rollup/plugin-babel @babel/core @babel/preset-env

在项目根目录下创建rollup.config.js

// rollup.config.js
import vue from 'rollup-plugin-vue'
import commonjs from '@rollup/plugin-commonjs'
import resolve from '@rollup/plugin-node-resolve'
import babel from '@rollup/plugin-babel'

export default {
  input: 'src/index.js',
  output: {
    format: 'esm',
    file: 'dist/my-component-library.esm.js'
  },
  plugins: [
    resolve(),
    commonjs(),
    vue(),
    babel({ babelHelpers: 'bundled', presets: ['@babel/preset-env'] })
  ],
  external: ['vue']
}

package.json中添加以下字段:

{
  "main": "dist/my-component-library.common.js",
  "module": "dist/my-component-library.esm.js",
  "scripts": {
    "build": "rollup -c"
  }
}

6. 构建项目

运行构建命令:

npm run build

7. 发布到npm

确保你已经登录npm账户,并更新package.json中的名称、版本、描述等信息。

npm login
npm publish --access public

8. 使用你的库

在其他项目中使用你的库:

npm install my-component-library

在项目中引入并使用:

import { createApp } from 'vue'
import App from './App.vue'
import MyComponentLibrary from 'my-component-library'

const app = createApp(App)
app.use(MyComponentLibrary)
app.mount('#app')

这样,你就完成了一个简单的Vue 3组件库的创建和发布。可以不断添加更多组件,并优化你的库。

遇到问题? 点击跳转的问题笔录