背景

假设我们要开发一个工具库,导出模块 A,B,C 现在希望他们能达到最大程度的 Tree shake,因此我们决定导出多个文件。

写个打包脚本

//  scripts/build.ts

import { build } from "vite";
import { dirname, resolve } from "path";
import { fileURLToPath } from "url";
import terser from "@rollup/plugin-terser";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export const r = (...args: string[]) =>
  resolve(__dirname, "..", ...args).replace(/\\/g, "/");

//  在这里定义你需要打包的模块
const files = ["A.ts", "B.ts", "C.ts"];

for (let fileName of files) {
  const filePath = r(`src/${fileName}`);
  const name = fileName.split(".")[0];

  build({
    root: r("src"),
    build: {
      outDir: r("dist"),
      emptyOutDir: false,
      sourcemap: false,
      cssCodeSplit: false,
      lib: {
        entry: filePath,
        name: name,
        formats: ["es"],
      },
      rollupOptions: {
        output: {
          entryFileNames: `${name}.js`,
        },
        plugins: [terser()],
      },
    },
  });
}

配置 package.json

{
  "name": "mymodules",
  "private": false,
  "version": "0.0.1",
  "type": "module",
  "main": "./dist/A.js",
  "module": "./dist/A.js",
  "types": "./dist/A.d.ts",
  "exports": {
    ".": "./dist/A.js",
    "./A": "./dist/A.js",
    "./B": "./dist/B.js",
    "./C": "./dist/C.js"
  },
  "typesVersions": {
    "*": {
      "A": ["./dist/A.d.ts"],
      "B": ["./dist/B.d.ts"],
      "C": ["./dist/C.d.ts"]
    }
  },
  "files": ["dist"],
  "scripts": {
    "build": "run-s build:*",
    "build:clear": "rimraf dist",
    "build:js": "esno scripts/build.ts",
    "build:type": "tsc -p ./tsconfig.json -emitDeclarationOnly"
  }
}