You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用web-nfc.d.ts时遭遇@babel/plugin-transform-typescript构建错误求助

解决React+TypeScript中web-nfc.d.ts导致的Babel构建错误

1. 检查Babel插件/预设的执行顺序

错误核心是@babel/plugin-transform-typescript必须在类相关插件(如@babel/plugin-transform-class-properties、@babel/plugin-transform-private-methods等)之前执行。

打开你的Babel配置文件(.babelrc、babel.config.json或package.json里的babel字段),确保顺序符合要求:

{
  "presets": [
    "@babel/preset-react",
    "@babel/preset-typescript" // 用预设的话,它内置transform-typescript插件,必须放在类插件相关配置前
  ],
  "plugins": [
    "@babel/plugin-transform-typescript", // 单独用插件时,必须放在插件列表最前面
    "@babel/plugin-transform-class-properties",
    "@babel/plugin-transform-private-methods"
  ]
}

注意:不要同时混用@babel/preset-typescript和单独的@babel/plugin-transform-typescript,避免冲突,优先使用预设。

2. 检查web-nfc.d.ts的语法正确性

确保类型定义文件中declare的使用符合TypeScript规范,不要在类内部错误使用declare。示例正确的web-nfc类型声明片段:

declare interface NFC extends EventTarget {
  watch(options?: NFCWatchOptions): Promise<NFCWatchRegistration>;
  cancelWatch(id?: number): Promise<void>;
  push(message: NFCMessage, options?: NFCPushOptions): Promise<void>;
}

declare var nfc: NFC | undefined;

如果你的web-nfc.d.ts或业务代码中有类内部的declare字段,调整为合法写法:

// 错误写法
class NFCService {
  declare nfcInstance: NFC; // React组件类中无需用declare,直接定义类型即可
}

// 正确写法
class NFCService {
  nfcInstance: NFC | undefined;
}

3. 排查tsconfig.json的冲突配置

检查tsconfig.json的compilerOptions,避免与Babel转换冲突:

  • 关闭isolatedModules(开启状态可能导致Babel处理declare时出错)
  • 确保declaration设为false(用Babel处理TypeScript时,不需要tsc生成声明文件)
    示例配置:
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "jsx": "react-jsx",
    "strict": true,
    "isolatedModules": false,
    "declaration": false
  }
}

4. 清除缓存并重新构建

缓存可能导致配置不生效,执行以下操作:

# 清除Node模块缓存
rm -rf node_modules/.cache
# 若使用Create React App,执行缓存清理
npm run clean
# 可选:重新安装依赖
npm install
# 重新构建项目
npm run build

5. 排查其他Babel插件干扰

如果项目使用了@babel/plugin-proposal-decorators等类相关插件,确保它们的顺序在@babel/plugin-transform-typescript之后,避免抢占转换顺序。

内容的提问来源于stack exchange,提问作者myjJustin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 13:21:11