Skip to content

Instantly share code, notes, and snippets.

@morlay
Last active November 8, 2023 03:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save morlay/0bfec1bffd2a3196efa08a5d6bb45015 to your computer and use it in GitHub Desktop.
Save morlay/0bfec1bffd2a3196efa08a5d6bb45015 to your computer and use it in GitHub Desktop.
Migrate to Bun from NodeJS

Package Manager (from pnpm)

清空 node_modulespnpm-lock.yaml

find . -name 'node_modules' -type d -prune -print -exec rm -rf '{}' \;
rm pnpm-lock.yaml

bun install 即可

常用命令

  • pnpm run <script> => bun run <script>
  • pnpm exec <script> => bunx --bun <script>
  • pnpm up --latest => bun update --latest --save

Registry 切换

bunfig.toml 换成环境变量即可,方便 CI 注入

[install]  
registry = "$NPM_REGISTRY"  
  
[install.scopes]  
"@innoai-tech" = { url = "$INNOAI_TECH_NPM_REGISTRY", token = "$INNOAI_TECH_NPM_REGISTRY_AUTH_TOKEN" }

发布版本

bun 暂时没有提供,可用 @morlay/bunpublish

bunx @morlay/bunpublish

借用 bunfig.toml 的配置

[install]
registry = { url = "https://registry.npmjs.org/", token = "$NPM_AUTH_TOKEN" }

发布可兼容 Node 的 Package

bun 有一个特殊的 export condition

Shipping TypeScript — Note that Bun supports the special "bun" export condition. If your library is written in TypeScript, you can publish your (un-transpiled!) TypeScript files to npm directly. If you specify your package's *.ts entrypoint in the "bun" condition, Bun will directly import and execute your TypeScript source files.

https://bun.sh/docs/runtime/modules#importing-packages

我们可以利用这个特性,直接发布 TypeScript。 也可以发布 bun 和 node 同时支持的 Package.

{
  "name": "foo",
  "version": "0.1.0",
  "type": "module",
  "exports": {
    ".": {
       // 需要放在第一个
	  "bun": "./src/index.ts",
	   // bundle 产物
	  "types": "./index.d.ts",
	  "import": "./index.mjs"
    }
  }
}

Monorepo

移动 pnpm-workspace.yamlpackage.jsonworkspaces: string[] ,即可 对于

因为有 export condition —— bun 的存在, 对应 TypeScript 项目,子 package 的配置可以进一步简化, 在私有项目中,更是可以直接提交 TypeScript 源文件。 并且作为依赖项,直接安装 git+https://github.com/x/x.git

Testing (from vitest)

替换 "vitest"bun:test 即可

dom 测试

创建文件 ./tool/happydom.ts

import { GlobalRegistrator } from "@happy-dom/global-registrator";  
  
// https://github.com/oven-sh/bun/issues/6044#issuecomment-1743414281  
const global = {  
  console: console  
};  
  
GlobalRegistrator.register();  
  
Object.assign(window, global);

修改 bunfig.toml

[test]  
preload = "./tool/happydom.ts"

展望

Node.js 的 API 兼容性还不完整,要彻底代替 Node.js 还有很长的路需要走。 但作为 Web 前端的构建工具是足够的了。 由于 io 的优化,vite/rollup 的体验进一步提升。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment