首先,确保你已经拥有了npm账号,并且安装了Node.js环境。
- 创建组件库项目:
mkdir my-component-library
cd my-component-library
npm init -y
- 安装依赖:
npm install --save-dev rollup @vue/compiler-sfc
npm install --save-dev rollup-plugin-vue @vue/compiler-sfc
npm install --save-dev @rollup/plugin-node-resolve
npm install --save-dev rollup-plugin-terser
- 创建rollup配置文件rollup.config.js:
import { defineConfig } from 'rollup';
import vue from 'rollup-plugin-vue';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';
export default defineConfig({
input: 'index.js', // 入口文件
output: [
{
file: 'dist/my-component-library.cjs.js',
format: 'cjs',
},
{
file: 'dist/my-component-library.esm.js',
format: 'es',
},
],
plugins: [
vue({
compileTemplate: true,
css: true,
}),
nodeResolve(),
terser(),
],
});
- 创建入口文件index.js:
// 引入你的组件
export { default as MyButton } from './components/MyButton.vue';
// 继续引入其他组件...
- 创建组件模板MyButton.vue:
<template>
<button class="my-button">Click Me</button>
</template>
<script>
export default {
name: 'MyButton',
// 组件的其他选项...
};
</script>
<style scoped>
.my-button {
padding: 10px 20px;
background-color: #f76a26;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
- 创建你的组件库入口文件my-component-library.js:
import MyButton from './components/MyButton.vue';
export { MyButton };
- 创建一个简单的README.md文件描述你的组件库。
- 配置package.json发布脚本:
{
"name": "my-component-library",
"version": "1.0.0",
"scripts": {
"build": "rollup -c"
},
"main": "dist/my-component-library.cjs.js",
"module": "dist/my-component-library.esm.js",
"files": [
"dist",
"components"
],
"peerDependencies": {
"vue": "^3.0.0"
},
"publishConfig": {
"access": "public"
}
}
- 构建组件库:
npm run build
- 登录到你的npm账号:
npm login
- 发布到npm:
npm publish
使用unplugin-vue-components插件按需引入组件:
首先安装unplugin-vue-components和unplugin-auto-import:
npm install --save-dev unplugin-vue-components unplugin-au