vue3 + ts + tailwindcss 开发组件库,并打包上传npm

3,460 阅读2分钟

创建 vue 项目

npm init vite my-project
// 选择vue3 + typescript

安装 tailwindcss

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest

运行命令生成 tailwind.config.js 以及 postcss.config.js 配置文件

npx tailwindcss init -p

修改 tailwind.config.js 里的 purge

purge: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}']

创建 ./src/index.css 文件

@tailwind base;
@tailwind components;
@tailwind utilities;

现在就可以正常使用tailwindcss了。

编写组件

  1. 创建组件 ./src/component/VButton.vue
<template>
  <div class="w-20 h-10 rounded-3xl bg-green-600 flex justify-center items-center text-white font-bold shadow-lg">
    <slot />
  </div>
</template>

<script setup lang="ts">
</script>
  1. 添加入口文件 ./src/index.ts
// tailwindcss
import './index.css'
// 组件
export { default as VButton } from './components/VButton.vue'

打包配置

vite

vite 配置为 lib 模式

// vite.config.ts
const path = require("path");
const { defineConfig } = require("vite");

module.exports = defineConfig({
  build: {
    lib: {
      entry: path.resolve(__dirname, "src/index.ts"),
      name: "MyLib",
      fileName: (format) => `my-lib.${format}.js`,
    },
    rollupOptions: {
      // make sure to externalize deps that shouldn't be bundled
      // into your library
      external: ["vue"],
      output: {
        // Provide global variables to use in the UMD build
        // for externalized deps
        globals: {
          vue: "Vue",
        },
      },
    },
  },
});

执行打包命令 npm run build 就可以看到生成了 dist 文件。

如果 __dirnamepathts 错误,则需要安装 @types/node:

npm i -D @types/node

package.json

配置的 jscss 的引入地址:

 "files": [
    "dist"
  ],
  "main": "./dist/my-lib.umd.js",
  "module": "./dist/my-lib.es.js",
  "exports": {
    ".": {
      "import": "./dist/my-lib.es.js",
      "require": "./dist/my-lib.umd.js"
    },
    "./style.css": {
      "import": "./dist/style.css"
    }
  },

组件测试

  1. 安装本地包
// 打包
npm run build

// 压缩生成 my-lib.tgz
npm pack

// 安装压缩包
npm i my-lib.tgz
  1. 引入测试
<template>
  <VButton primary>点我</VButton>
</template>

<script setup lang="ts">
import { VButton } from 'my-lib'
import 'my-lib/style.css'
</script>

类型声明

上述代码此刻会报 typescript 类型错误,我们需要使用 vue-tsc 来处理。

vue-tsc 是一个类型检测工具,它也可以为我们自动创建类型声明文件。

  1. 修改 tsconfig.ts 文件:
"compilerOptions": {
    ...
    "outDir": "dist",
    "declaration": true
}
  1. 修改 build 脚本:
"build": "vite build && vue-tsc --declaration --emitDeclarationOnly && mv dist/src dist/types"

运行 builddist 文件夹下额外生成 types 目录,默认是 src 目录,最后操作把它移动到了 types 中。

  1. package.json 文件中添加类型声明位置:
"types": "./dist/types/index.d.ts"
  1. 重新打包测试,不再报类型错误。

发布

测试无误后,发布到npm上

npm loigin
npm publish

github项目地址