使用vite构建Vue3组件库,发布npm包

文摘   科技   2024-07-13 00:00   吉林  

When we need to encapsulate some public component libraries twice in different projects, centralized coding is particularly concise, not only makes the code can be centrally processed, batch upgraded, but also can be normalized in the code catalog, therefore, packaging a common ui library is a relatively necessary process

当我们在不同项目中都需要二次封装一些公共组件库的时候,集中编码显得尤为简练, 不仅仅使得代码能够集中处理,批量升级,也能在代码目录上进行规范性整理,因此,封装一个通用的ui库,是一个比较必须的过程.

1.创建项目vite 脚手架

bun create vue@latest

Vue.js - The Progressive JavaScript Framework

√ 请输入项目名称:ck-ui-plus
√ 是否使用 TypeScript 语法?... 否 / 是
√ 是否启用 JSX 支持?... 否 / 是
√ 是否引入 Vue Router 进行单页面应用开发?... 否 / 是
√ 是否引入 Pinia 用于状态管理?... 否 / 是
√ 是否引入 Vitest 用于单元测试?... 否 / 是
√ 是否要引入一款端到端(End to End)测试工具? » 不需要
√ 是否引入 ESLint 用于代码质量检测?... 否 / 是
√ 是否引入 Vue DevTools 7 扩展用于调试? (试验阶段) ... 否 / 是

正在初始化项目 ck-ui-plus...

项目初始化完成,可执行以下命令:

cd ck-ui-plus
bun install
bun dev

bun install v1.1.18 (5a0b9352)

+ @vitejs/plugin-vue@5.0.5
+ @vitejs/plugin-vue-jsx@4.0.0
+ @vue/test-utils@2.4.6
+ jsdom@24.1.0
+ vite@5.3.3
+ vite-plugin-vue-devtools@7.3.5
+ vitest@1.6.0 (v2.0.2 available)
+ pinia@2.1.7
+ vue@3.4.31
+ vue-router@4.4.0

281 packages installed [39.80s] 

2.编写组件封装

<script setup name="ckButton"></script>

<template>
  <button class="ck-btn">
    <slot></slot>
  </button>
</template>

<style scoped>
.ck-btn {
  appearance: none;
  border: none;
  outline: none;
  background#fff;
  text-align: center;
  border1px solid transparent;
  border-radius4px;
  cursor: pointer;
}
</style>

3.组件导出

import Button from "../components/button/index.vue";
const components = [Button];
const install = function (Vue) {
  if (install.installed) return;
  install.installed = true;
  // 遍历并注册全局组件
  components.map((component) => {
    Vue.component(component.name, component);
  });
};

if (typeof window !== "undefined" && window.Vue) {
  install(window.Vue);
}

export default {
  // 导出的对象必须具备一个 install 方法
  install,
  // 组件列表
  ...components,
};

4.本地验证组件是否可以用

import './assets/main.css'

import { createApp } from 'vue'

import ckUI from './package'//导入

import App from './App.vue'

const app = createApp(App)

app.use(ckUI) //注册
app.mount('#app')

使用

<template>
  <main>
    <ckButton size="large" type="primary">我是ckButton组件</ckButton>
  </main>
</template>

然后在终端输入bun run dev运行 显示出来就成功了

5.配置vite.lib.config.js文件

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import vueDevTools from "vite-plugin-vue-devtools";
import { resolve } from "path";
import { fileURLToPath, URL } from "node:url";
import path from "path";
const pathResolve = (dir) => {
  return resolve(__dirname, ".", dir);
};
// https://cn.vitejs.dev/config/build-options#build-target
export default defineConfig({
  plugins: [vue(), vueJsx(), vueDevTools()],
  resolve: {
    alias: {
      "@"fileURLToPath(new URL("./src"import.meta.url)),
    },
  },
  build: {
    outDir"lib"// 打包输出目录
    // outDir: "dist", // 打包输出目录
    lib: {
      entrypathResolve("./src/package"),
      // entry: path.resolve(__dirname, "./src/ck-ui/index.js"), //指定组件编译入口文件
      // 组件库名字
      name"ck-ui-plus",
      fileName"index"//fileName: (format) => `tmes.${format}.js`,
      // 输出格式
      formats: ["es"],
    },
    emptyOutDirtrue,
    rollupOptions: {
      // 确保外部化处理那些你不想打包进库的依赖
      external: ["vue"],
      output: {
        // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
        globals: {
          vue"Vue",
        },
      },
    },
  },
});

6.运行打包命令

package.json可以放在外面,注意main路径,也可以放进lib里面,把main路径改下就行

{
  "name""ck-ui-plus",
  "version""0.0.4",
  "description""vite制作npm包",
  "private"false,
  "keywords": ["ck-ui""ck-ui-plus""ck-ui"],
  "type""module",
  "scripts": {
    "lib""vite build --config vite.lib.config.js",
  },
  "main""lib/index.js",//npm读取路径
  "author""caokun",
  "license""ISC"
}

在终端使用bun run lib ,显示lib文件夹,可以在本地测试,是否显示组件

import "../lib/style.css"
import ckUI from '../lib/index.js'
app.use(ckUI) //注册

7.上传到npm官网

此处要切换到官网地址,进行登录npm账号

npm config get registry   
https://registry.npmmirror.com //代理加速地址

npm config set registry https://registry.npmjs.org  

npm config get registry 
https://registry.npmjs.org  //官网地址

npm login //登录

npm publish //推送

npm notice 
npm notice 📦  ck-ui-plus@0.0.4
npm notice === Tarball Contents === 
npm notice 39B   .vscode/extensions.json
npm notice 2.3kB README.md
npm notice 4.3kB lib/favicon.ico        
npm notice 955B  lib/index.js
npm notice 723B  lib/style.css
npm notice 790B  package.json
npm notice === Tarball Details === 
npm notice name:          ck-ui-plus
npm notice version:       0.0.4
npm notice filename:      ck-ui-plus-0.0.4.tgz
npm notice package size:  3.4 kB
npm notice unpacked size9.1 kB
npm notice shasum:        22a66d9b28535a9905e3701208418bbe8d3f698f
npm notice integrity:     sha512-k5pkSABXwsoLp[...]q/m2l+TwlQEkA==
npm notice total files:   6
npm notice 
npm notice Publishing to https://registry.npmjs.org with tag latest and default access
+ ck-ui-plus@0.0.4

重名会报错 换个名字就行 "name": "ck-ui-plus"

版本一样会报错 "version": "1.0.3"

8.使用npm组件

下载

bun install ck-ui-plus

使用

import "../node_modules/ck-ui-plus/lib/style.css"
import ckUI from 'ck-ui-plus'
app.use(ckUI) //注册

运行

bun run dev

我希望这篇文章对您有所帮助。

Thank you for reading.

如何获取这份资料

关注公众号全栈开发ck」,留言关注转发即可获取源码

推荐阅读

全栈开发ck
叩首问路,码梦为生