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

Babel Parser无法解析`import type`声明问题求助

解决Babel Parser解析import type语句报错的问题

问题原因

import type是TypeScript专属的语法特性,默认的@babel/parser未启用TypeScript支持,因此无法识别该语法,导致抛出Unexpected token, expected "from"错误。errorRecovery和strictMode配置仅针对JavaScript语法的容错或严格校验,不影响TypeScript语法的解析能力。

解决步骤

  1. 确保已安装@babel/parser依赖
  2. 在解析配置中添加typescript插件,开启TypeScript语法支持

修改后的示例代码:

const parser = require('@babel/parser');

const code = "import type {Element} from 'react-devtools-shared/src/frontend/types';";
const ast = parser.parse(code, {
  sourceType: "unambiguous",
  plugins: ['typescript'] // 启用TypeScript插件以识别`import type`语法
});

额外说明

如果你的代码中同时包含JSX语法,需要在插件数组中额外添加jsx:

plugins: ['typescript', 'jsx']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 03:02:03