Logo of unbuild

unbuild

一个统一的 JavaScript 构建系统。

一个统一的 JavaScript 构建系统

📦 优化型打包器

强大的基于 Rollup 的打包器,支持 TypeScript 并生成 CommonJS 和模块格式 + 类型声明。

🪄 自动化配置

自动从 package.json 中推断构建配置和入口。

📁 无打包构建

mkdist 集成,通过文件到文件转译生成无打包的 dist 文件。

✨ 被动观察器

使用 jiti 一次性生成 dist 存根,你可以在开发过程中尝试链接你的项目,而无需观察和重复构建。

✍ 类型生成器

untyped 集成。

✔️ 安全构建

自动检查各种构建问题,例如潜在的缺失未使用的依赖项,并使 CI 失败。

CLI 输出还包括输出大小和导出,以便快速检查。

用法

创建 src/index.ts

export const log = (...args) => {
  console.log(...args);
};

更新 package.json

{
  "type": "module",
  "exports": {
    ".": {
      "import": "./dist/index.mjs",
      "require": "./dist/index.cjs"
    }
  },
  "main": "./dist/index.cjs",
  "types": "./dist/index.d.ts",
  "files": ["dist"]
}

注意 你可以在 unjs/template 中找到更完整的项目设置示例。

使用 unbuild 进行构建

npx unbuild

配置会自动从 package.json 中映射到 src/ 目录的字段中推断。如需更多控制,请继续阅读下一节。

配置

创建 build.config.ts

export default {
  entries: ["./src/index"],
};

你可以使用 package.json 中的 unbuild 键或 build.config.{js,cjs,mjs,ts,mts,cts,json} 来指定配置。

查看选项 此处

示例

import { defineBuildConfig } from "unbuild";

export default defineBuildConfig({
  // If entries is not provided, will be automatically inferred from package.json
  entries: [
    // default
    "./src/index",
    // mkdist builder transpiles file-to-file keeping original sources structure
    {
      builder: "mkdist",
      input: "./src/package/components/",
      outDir: "./build/components",
    },
  ],

  // Change outDir, default is 'dist'
  outDir: "build",

  // Generates .d.ts declaration file
  declaration: true,
});

或者对于多个构建,你可以声明一个配置数组

import { defineBuildConfig } from "unbuild";

export default defineBuildConfig([
  {
    // If entries is not provided, will be automatically inferred from package.json
    entries: [
      // default
      "./src/index",
      // mkdist builder transpiles file-to-file keeping original sources structure
      {
        builder: "mkdist",
        input: "./src/package/components/",
        outDir: "./build/components",
      },
    ],

    // Change outDir, default is 'dist'
    outDir: "build",

    /**
     * * `compatible` means "src/index.ts" will generate "dist/index.d.mts", "dist/index.d.cts" and "dist/index.d.ts".
     * * `node16` means "src/index.ts" will generate "dist/index.d.mts" and "dist/index.d.cts".
     * * `true` is equivalent to `compatible`.
     * * `false` will disable declaration generation.
     * * `undefined` will auto detect based on "package.json". If "package.json" has "types" field, it will be `"compatible"`, otherwise `false`.
     */
    declaration: "compatible",
  },
  {
    name: "minified",
    entries: ["./src/index"],
    outDir: "build/min",
    rollup: {
      esbuild: {
        minify: true,
      },
    },
  },
]);

💻 开发

  • 克隆此仓库
  • 使用 corepack enable 启用 Corepack (Node.js < 16.10 请使用 npm i -g corepack)
  • 使用 pnpm install 安装依赖项
  • 使用 pnpm dev 运行交互式测试

许可

MIT