使用Vite来打包并发布一个npm包

1,595 阅读1分钟

库模式

Vite提供了便捷的库模式用来开发第三方依赖并进行打包,当你想要将你的某个组件打包并发布到npm上是,是一个很好的选择。

配置

// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { resolve } from "path";
​
export default defineConfig({
  plugins: [react()],
  build: {
    lib: {
      entry: resolve(__dirname, "src/components/LazyPictures.tsx"), // 打包的入口文件
      name: "LazyPictures", // 包名
      // formats: ['es', 'umd'], // 打包模式,默认是es和umd都打
      fileName: (format) => `lazy-pictures.${format}.js`,
    },
    rollupOptions: {
      // 确保外部化处理那些你不想打包进库的依赖
      external: ["react"],
      output: {
        // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
        globals: {
          react: "React",
        },
      },
    },
    outDir: "lib", // 打包后存放的目录文件
  },
});

入口文件这里,可以直接指定你要打包的那个组件,也可以指定一个入口

TypeScript声明文件

由于Vite仅仅只是将我们指定的文件进行打包,所以要生成d.ts文件,我们需要借助tsconfigtsc命令

// tsconfig.build.json
{
  "extends": "./tsconfig.json", // 拓展 tsconfig.json 的配置
  "compilerOptions": {
    "noEmit": false, // 允许生成文件
    "declaration": true, // 需要设置为 true 来支持类型
    "emitDeclarationOnly": true, // 只生成类型文件
    "declarationDir": "lib" // 类型文件的导出目录
  },
  "include": ["src/components/LazyPictures.tsx"] // 编译目标仅为 src 文件夹下的文件
}

package.json文件的配置

{
    "name": "lazy-pictures",
    "version": "0.0.3",
    "description": "React image loading component",
    "files": [
        "lib"
    ],
    "peerDependencies": {
        "react": ">=17.0.0"
    },
    "license": "MIT",
    "repository": "https://github.com/hjc0930/lazy-pictures",
    "main": "./lib/lazy-pictures.umd.js",
    "module": "./lib/lazy-pictures.es.js",
    "types": "./lib/lazyPictures.d.ts",
    "exports": {
        ".": {
            "import": "./lib/lazy-pictures.es.js",
            "require": "./lib/lazy-pictures.umd.js"
        }
    },
    "scripts": {
        "dev": "vite",
        "build": "vite build && tsc -p tsconfig.build.json", // 修改build命令在运行tsc时读取tsconfig.build.json文件
        "preview": "vite preview"
    },
}