跳到主要内容

bun

基础

安装

# mac & linux
curl -fsSL https://bun.sh/install | bash
# windows
powershell -c "irm bun.sh/install.ps1|iex"

更新

bun upgrade

包管理

# 安装依赖
bun install
# 添加依赖
bun add <package>
# 移除依赖
bun remove <package>
# 更新全部依赖
bun update
# 自动安装并运行
bunx cowsay "Hello world!"

Monorepo

新建项目

# 新建一个空项目
bun init

# 根据组件/npm/github/本地模板创建项目
bun create

项目结构

├── README.md
├── bun.lock
├── package.json
├── tsconfig.json
└── apps # web 应用
├── app-a
│ ├── index.ts
│ ├── package.json
│ └── tsconfig.json
└── packages # 内部使用包
├── pkg-a
│ ├── index.ts
│ ├── package.json
│ └── tsconfig.json
└── libs # 外部使用包
├── lib-a
│ ├── index.ts
│ ├── package.json
│ └── tsconfig.json

Workspace

{
"name": "my-project",
"version": "1.0.0",
"workspaces": ["packages/**", "!packages/**/test/**", "!packages/**/template/**"],
"devDependencies": {
"example-package-in-monorepo": "workspace:*"
}
}

项目调试

命令

# 运行
bun run index.ts
# watch mode
bun --watch run index.ts
# 调试
bun --inspect index.ts

vscode 拓展

调试网络请求

  • App.tsx 添加环境变量;
process.env.BUN_CONFIG_VERBOSE_FETCH = "curl";

打包项目

js 打包

await Bun.build({
entrypoints: ["./index.tsx"],
outdir: "./build",
});

cli 打包

bun build ./index.tsx --outdir ./build

工程化

husky & commitlint & biome & lint-staged

# husky
bun add --dev husky
bunx husky init

# commitlint
bun add -d @commitlint/cli @commitlint/config-conventional
echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js
echo "bunx commitlint --edit \$1" > .husky/commit-msg

# biome
bun add -D -E @biomejs/biome

# lint-staged
bun add --dev lint-staged
echo "bunx lint-staged" > .husky/pre-commit

配置

biome
  • biome.json;
{
"$schema": "https://biomejs.dev/schemas/2.3.9/schema.json",
"files": {
"ignoreUnknown": false
},
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"nursery": {
"useSortedClasses": "error"
}
}
},
"assist": {
"enabled": true,
"actions": {
"recommended": true
}
},
"formatter": {
"enabled": true,
"indentStyle": "tab"
}
}
lint-staged
  • lint-staged.config.js;
/**
* @filename: lint-staged.config.js
* @type {import('lint-staged').Configuration}
*/
export default {
"*.{js,ts,cjs,mjs,d.cts,d.mts,jsx,tsx,json,jsonc}": ["biome check --write"],
};