要安装 Bun 内置 API 的类型定义,请安装 bun-types。
bun add -d bun-types
然后在 tsconfig.json 中的 compilerOptions.types 中包含 “bun-types”:
{"compilerOptions": {"types": ["bun-types"]}}
至此,您应该能够在 TypeScript 文件中引用 Bun 全局变量,而不会看到编辑器中的错误。
推荐的 compileroptions
Bun 支持诸如顶级 await、JSX 和扩展的 .ts 导入等 TypeScript 默认不允许的功能。下面是 Bun 项目的一组推荐编译器选项,以便您可以使用这些功能而不会看到来自 TypeScript 的编译器警告。
{"compilerOptions": {// add Bun type definitions"types": ["bun-types"],// enable latest features"lib": ["esnext"],"module": "esnext","target": "esnext",// if TS 5.x+"moduleResolution": "bundler","noEmit": true,"allowImportingTsExtensions": true,"moduleDetection": "force",// if TS 4.x or earlier// "moduleResolution": "nodenext","jsx": "react-jsx", // support JSX"allowJs": true, // allow importing `.js` from `.ts`"esModuleInterop": true, // allow default imports for CommonJS modules// best practices"strict": true,"forceConsistentCasingInFileNames": true,"skipLibCheck": true,"composite": true,"downlevelIteration": true,"allowSyntheticDefaultImports": true}}
如果在新目录中运行 bun init,则会为您生成此 tsconfig.json 文件。
bun init
DOM 类型
不幸的是,为 types 设置值意味着 TypeScript 将忽略其他全局类型定义,包括 lib: ["dom"]。如果您需要将 DOM 类型添加到项目中,请在项目的任何 TypeScript 文件的顶部添加以下三斜杠指令。
/// <reference lib="dom" />/// <reference lib="dom.iterable" />
