要安装 Bun 内置 API 的类型定义,请安装 bun-types

  1. bun add -d bun-types

然后在 tsconfig.json 中的 compilerOptions.types 中包含 “bun-types”:

  1. {
  2. "compilerOptions": {
  3. "types": ["bun-types"]
  4. }
  5. }

至此,您应该能够在 TypeScript 文件中引用 Bun 全局变量,而不会看到编辑器中的错误。

推荐的 compileroptions

Bun 支持诸如顶级 await、JSX 和扩展的 .ts 导入等 TypeScript 默认不允许的功能。下面是 Bun 项目的一组推荐编译器选项,以便您可以使用这些功能而不会看到来自 TypeScript 的编译器警告。

  1. {
  2. "compilerOptions": {
  3. // add Bun type definitions
  4. "types": ["bun-types"],
  5. // enable latest features
  6. "lib": ["esnext"],
  7. "module": "esnext",
  8. "target": "esnext",
  9. // if TS 5.x+
  10. "moduleResolution": "bundler",
  11. "noEmit": true,
  12. "allowImportingTsExtensions": true,
  13. "moduleDetection": "force",
  14. // if TS 4.x or earlier
  15. // "moduleResolution": "nodenext",
  16. "jsx": "react-jsx", // support JSX
  17. "allowJs": true, // allow importing `.js` from `.ts`
  18. "esModuleInterop": true, // allow default imports for CommonJS modules
  19. // best practices
  20. "strict": true,
  21. "forceConsistentCasingInFileNames": true,
  22. "skipLibCheck": true,
  23. "composite": true,
  24. "downlevelIteration": true,
  25. "allowSyntheticDefaultImports": true
  26. }
  27. }

如果在新目录中运行 bun init,则会为您生成此 tsconfig.json 文件。

bun init

DOM 类型

不幸的是,为 types 设置值意味着 TypeScript 将忽略其他全局类型定义,包括 lib: ["dom"]。如果您需要将 DOM 类型添加到项目中,请在项目的任何 TypeScript 文件的顶部添加以下三斜杠指令。

  1. /// <reference lib="dom" />
  2. /// <reference lib="dom.iterable" />