@b9g/libuild

中文文档
0.2.31发布于 2026/11/03MITTypeScriptES Module构建来源已验证近 30 天下载 3658

Zero-config library builds

原始使用文档
文档目录24 节
  1. Installation
  2. Usage
  3. Features
  4. Convention = Configuration
  5. Entry Points
  6. Output Structure
  7. Format Control
  8. Export Aliases
  9. Package.json Transformations
  10. Examples
  11. Simple Library
  12. Library with CLI
  13. ESM-Only Library
  14. Multi-Format with UMD
  15. Generated Package.json Exports
  16. Commands
  17. libuild build (default)
  18. libuild build --save
  19. libuild publish
  20. Requirements
  21. Testing: libuild test
  22. Coverage
  23. In-source tests
  24. License

libuild

Zero-config library builds with ESBuild.

Libuild is a build tool for JavaScript/TypeScript libraries which publish to NPM. It solves ESM/CJS support, type generation, and produces clean packages with just the files and configuration needed by consumers.

Installation

npm install -D @b9g/libuild
bun add -d @b9g/libuild

Usage

# Build your library (development mode - no package.json changes)
libuild build

# Build and update package.json for npm link
libuild build --save

# Build and publish to npm
libuild publish

Features

  • No configuration - Source files and standard package.json are all you need
  • Multiple formats - Supports ESM, CJS, UMD, and generates d.ts files
  • Clean output - Only necessary files and fields go into the package
  • Development-friendly - NPM link just works and changes can be saved to package.json

Convention = Configuration

Entry Points

  • Library modules: All top-level .js/.ts files in src/ (excluding _ prefixed files)
  • Workers: A src/<name>.worker.ts is built to dist/<name>.worker.js but left out of exports. It is for code that is loaded by file path - new Worker(new URL("./decode.worker.js", import.meta.url), {type: "module"}) - which never goes through the exports map, so there is nothing to make public. ESM only.
  • CLI binaries: Any file referenced in package.json bin field gets compiled to standalone executable
  • UMD builds: If src/umd.ts exists, creates browser-compatible UMD build

Output Structure

  • Flat output: src/index.ts → dist/index.js - modules publish at the package root, so direct CDN URLs like cdn.jsdelivr.net/npm/<pkg>/index.js just work
  • Executables: bin/cli.ts → dist/bin/cli.js (bin/ stays a subdirectory)
  • ESM: .js files with ES module syntax
  • CommonJS: .cjs files for Node.js compatibility
  • TypeScript: .d.ts declaration files for all modules (when TypeScript is available); internal modules relocate together with their imports intact
  • Module augmentation: declare module blocks are preserved in .d.ts output
  • Code splitting: Dynamic imports create chunks in dist/_chunks/
  • Clean package.json: Optimized for consumers (no dev scripts)

Format Control

  • ESM-only: Remove the main field from package.json to skip CommonJS builds
  • CommonJS detection: Presence of main field enables .cjs builds
  • UMD builds: Add src/umd.ts for browser-compatible builds

Export Aliases

  • Legacy support: ./entry.js automatically aliases to ./entry
  • Package.json: Always exported as ./package.json
  • Custom exports: Existing exports in package.json are preserved and enhanced

Package.json Transformations

  • Development mode (default): Root package.json unchanged, no git noise
  • --save mode: Root package.json updated to point to ./dist/* artifacts for npm link
  • Dist package.json: Clean consumer-ready version with root-relative paths
  • Bin paths: Automatically transformed from src/ references to built artifacts
  • Exports field: Generated for all entry points with proper types-first ordering

Examples

Simple Library

Given this structure:

src/
  index.ts
  utils.ts
  _internal.ts  # ignored (underscore prefix)

Produces:

dist/
  index.js         # ESM
  index.cjs        # CommonJS
  index.d.ts       # TypeScript declarations
  utils.js
  utils.cjs
  utils.d.ts
  package.json     # Clean consumer version

Library with CLI

package.json:
{
  "bin": { "mytool": "src/cli.js" }
}

src/
  index.ts
  cli.ts

Produces:

dist/
  index.js
  index.cjs
  index.d.ts
  cli.js           # Compiled CLI (dual-runtime shebang, executable)
  cli.cjs
  cli.d.ts
  package.json     # bin: { "mytool": "cli.js" }

ESM-Only Library

To build only ESM (no CommonJS), remove the main field:

// package.json
{
  "name": "my-lib",
  "module": "dist/index.js",  // ESM entry
  "types": "dist/index.d.ts"
  // no "main" field = no CJS
}

Produces:

dist/
  index.js         # ESM only
  index.d.ts
  utils.js         # ESM only
  utils.d.ts
  package.json     # ESM-only exports

Multi-Format with UMD

src/
  index.ts
  utils.ts
  umd.ts         # Browser build entry

Produces:

dist/
  index.js
  index.cjs
  index.d.ts
  utils.js
  utils.cjs
  utils.d.ts
  umd.js           # UMD browser build
  package.json

Generated Package.json Exports

Dual format (ESM + CommonJS):

{
  "main": "index.cjs",
  "module": "index.js",
  "types": "index.d.ts",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "import": "./index.js",
      "require": "./index.cjs"
    },
    "./utils": {
      "types": "./utils.d.ts",
      "import": "./utils.js",
      "require": "./utils.cjs"
    },
    "./utils.js": {
      "types": "./utils.d.ts",
      "import": "./utils.js",
      "require": "./utils.cjs"
    },
    "./package.json": "./package.json"
  }
}

ESM-only (no main field in source):

{
  "module": "index.js",
  "types": "index.d.ts",
  "type": "module",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "import": "./index.js"
    },
    "./utils": {
      "types": "./utils.d.ts",
      "import": "./utils.js"
    },
    "./utils.js": {
      "types": "./utils.d.ts",
      "import": "./utils.js"
    },
    "./package.json": "./package.json"
  }
}

Root package.json (with --save):

{
  "main": "./dist/index.cjs",
  "module": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    }
  }
}

Commands

libuild build (default)

Builds your library in development mode:

  • Compiles all entry points to multiple formats
  • Generates TypeScript declarations
  • Creates optimized package.json files
  • Preserves root package.json (no git noise)

libuild build --save

Builds and updates root package.json for npm link:

  • Everything from libuild build
  • Updates root package.json to point to dist artifacts
  • Perfect for testing with npm link

libuild publish

Builds and publishes to npm:

  • Runs full build with --save
  • Warns if root package.json is not private
  • Publishes from dist directory with clean package.json

Requirements

  • Node.js 20.10+ or Bun 1.0+ (for running libuild)
  • TypeScript (optional, for .d.ts generation)
  • No runtime requirements for library consumers

Testing: libuild test

Runs your suite across runtimes with one command and one set of test files:

libuild test                        # bun, current directory
libuild test tests -p bun -p node   # both runtimes
libuild test -p deno                # deno, via `deno test`
libuild test -p chromium            # real browser via Playwright
libuild test path/to/one.test.ts    # single-file loop

Deno runs the same files through its own deno test, which bridges node:test into it, so no Deno-specific test API is needed, and the summary reads the same on all three runtimes.

Import the portable API from @b9g/libuild/test (describe/test/it/expect, hooks, test.concurrent, .each, and a cross-runtime toMatchSnapshot). Files run in per-file isolated processes with dependencies resolved from your node_modules; import.meta.url/.dirname/.filename and __dirname/__filename point at your source files, not the bundles.

Flags: --timeout <ms> is the per-file budget, and on bun it is also applied as the per-test timeout (bun defaults to 5s per test; without this, slow tests die before the file budget matters). --concurrency <n> caps how many files run at once — lower it for suites whose tests spawn their own processes. --filter <glob> selects files; -u updates snapshots; --debug keeps the browser open and preserves the bundle directory.

Coverage

libuild test --coverage -p node collects coverage on the node shards and prints a table after the run, with lines mapped back to your source files through the bundles' source maps. --coverage-reporter lcov html picks c8's reporters (default text); file reports go to coverage/, or --coverage-dir <dir>. Test files and declaration files are left out. Coverage is node-only: bun does not write V8 coverage for a bundle and deno writes its own format, so shards on those runtimes run as usual and collect nothing.

In-source tests

Tests can live in the module they cover, the way Rust's mod tests does. They share the module's closure, so they can reach helpers and state that is never exported:

const SEEN = new Map<string, number>();

function memoKey(a: number, b: number) { return `${a}:${b}`; }

export function addMemo(a: number, b: number) {
  const key = memoKey(a, b);
  if (SEEN.has(key)) { return SEEN.get(key)!; }
  const out = a + b;
  SEEN.set(key, out);
  return out;
}

if (import.meta.litest) {
  const {test, expect} = import.meta.litest;

  test("memoizes", () => {
    expect(addMemo(1, 2)).toBe(3);
    expect(SEEN.get(memoKey(1, 2))).toBe(3);   // never exported
  });
}

There is nothing to import: import.meta.litest is the test API, the same surface @b9g/libuild/test exports. libuild test injects it and runs these files alongside your *.test.* suite; any file under src/ containing the guard is discovered.

libuild build removes the block completely — the assertions, and any import only the test needed. Nothing about the published package reveals the tests were there, and consumers never need libuild installed to load your library.

Two things worth knowing:

  • Write the guard as if (import.meta.litest). Discovery looks for exactly that, so a test block behind a different expression is stripped from the build but never run.
  • Files containing in-source tests are syntax-minified in dist (if/continue collapsed to ||, and so on). Removing the block requires constant folding, which libuild applies per file rather than turning it on for the whole build — so modules without in-source tests keep byte-identical output.

The same guard gates test-only code that is not a test. A check that runs in a frame loop under test, and must not ship, sits behind if (import.meta.litest): in every test bundle the expression is the test API, so the check runs; in the build it is undefined and the guarded code is stripped, and a function only it called goes with it.

For TypeScript, add libuild's ambient declaration to your tsconfig.json:

{"compilerOptions": {"types": ["@b9g/libuild/litest.d.ts"]}}

Runtime notes:

  • bun cannot nest test() inside test() (oven-sh/bun#5090). Notably, ESLint's RuleTester registers nested subtests, so rule suites hit NotImplementedError on bun — either run those with -p node, or flatten RuleTester's hooks (RuleTester.describe = (_n, fn) => fn() inside one enclosing test) to stay portable.
  • libuild is ESM-only: packages declaring "type": "commonjs" are refused (packages with no type field are fine). CJS is produced only as the build's main-field fallback.

License

MIT

版本与发布记录

@b9g/libuild 共发布 57 个版本,首次发布于 2025/10/27;过去 12 个月发布了 46 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.2.31latest2026/11/034 天前
0.2.302026/10/1919 天前
0.2.292026/10/1622 天前
0.2.282026/10/1622 天前
0.2.272026/10/1623 天前
0.2.262026/10/0929 天前

关于 @b9g/libuild 的常见问题

@b9g/libuild 是什么?

Zero-config library builds

如何安装 @b9g/libuild?

在项目目录运行 npm install @b9g/libuild,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 libuild,可以用 npx libuild 直接运行。

@b9g/libuild 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@b9g/libuild 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@b9g/libuild 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.10.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@b9g/libuild 可以商用吗?

@b9g/libuild 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@b9g/libuild 的下载量有多少?

根据 npm 官方下载统计,@b9g/libuild 在 2026/10/08 – 2026/11/06 这 30 天内被下载 3,658 次,日均约 122 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@b9g/libuild 还在维护吗?

最新版本 0.2.31 发布于 2026/11/03(4 天前);至今共发布 57 个版本,其中过去 12 个月发布了 46 个;首次发布于 2025/10/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。