distpkg
v0.0.5
Published
Post-build tool that generates minimal package.json in dist/ and re-installs deps to ensure bundled code runs correctly
Maintainers
Readme
一个项目构建后的工具(一般用于(bun) 或者 node 等,打包成单文件后使用),在 dist 目录中生成精简的 package.json,然后在 dist 目录下通过再一次的 install 确保最终的代码可以执行正确
为什么需要在 install 一次?
因为可能存在某些包依赖了当下的环境,或者某些包在 runtime 时才会判断要去加载它依赖的包(这些包可能被直接安装到 node_modules/some-package 中)。所以我们需要把这些“特殊”的包单独拿出来。比如 foo,放在 dist/package.json 的 dependencies 中,这样在 dist 目录下通过再一次的 install 就可以确保代码执行正确!
为什么要打包?🤨
Why bundle?,让我们一起阅读这篇文章
特性
- 🚀 快速简单: 快速生成 dist/package.json
- 📦 灵活配置: 支持命令行选项和配置文件
- 🔧 可定制: 选择要包含的 package.json 字段
- 🌟 TypeScript 支持: 完整的 TypeScript 支持和类型定义
- 📝 自动排序: 自动排序 package.json 字段,适合强迫症
- ✅ 100% 测试覆盖率: 项目稳定可靠,质量有保障
- Bun 完美适配: 专为 Bun 单文件打包优化,无缝集成
安装
# pnpm
pnpm add -D distpkg
# bun
bun add -D distpkg
# npm
npm install -D distpkg
# yarn
yarn add -D distpkg快速开始
基本用法 (只需两步)
- 配置 package.json 中的 scripts
{
"scripts": {
"build": "pnpm run build:project && distpkg",
"build:project": "your build command"
}
}- 配置 distpkg.config.ts
// distpkg.config.ts
import { defineConfig } from 'distpkg';
export default defineConfig({
packageJson: {
dependencies: {
foo: '^1.0.0'
/* more dependencies */
}
}
});[!TIP] 在项目构建的时候,你应该排除 foo 包,如
"build": "bun build src/index.ts --target bun --outdir=dist --bytecode --minify --external foo"
命令行选项
Usage:
$ distpkg [...package-keys]
Commands:
[...package-keys] Keys to copy from project package.json to dist/package.json
For more info, run any command with the `--help` flag:
$ distpkg --help
Options:
-c, --config <filename> Use a custom config file
-d, --out-dir <dir> Output directory (default: dist)
--cwd <dir> Working directory (default: process.cwd())
-s, --sort Sort package.json (default: true)
-h, --help Display this message
-v, --version Display version number编程方式使用
import { build } from 'distpkg';
// your build js
// ...
const result = await build({
/* ... */
});
if (!result.success) {
console.error('Build failed with errors:', result.message);
}docker 部署
有了这个工具之后,我们的项目最佳实践应该如下(仅表示我个人):
install -> build -> cd dist -> install -> 打包成镜像 -> 部署到 docker -> 部署成功启动服务
License
Copyright (c) 2025-present, Zhifeng (Jeff) Wang
