Babel Parser无法解析`import type`声明问题求助
解决Babel Parser解析
import type语句报错的问题 问题原因
import type是TypeScript专属的语法特性,默认的@babel/parser未启用TypeScript支持,因此无法识别该语法,导致抛出Unexpected token, expected "from"错误。errorRecovery和strictMode配置仅针对JavaScript语法的容错或严格校验,不影响TypeScript语法的解析能力。
解决步骤
- 确保已安装
@babel/parser依赖 - 在解析配置中添加
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
相关产品推荐
相关产品推荐

