Vue项目用了@babel/preset-typescript为什么还是报TypeScript语法错误?

UX炳錦 阅读 31

在Vue3项目里配置了Babel和@babel/preset-typescript,但运行时还是提示“Unexpected token ‘;’ in JSON at position 12”这种错误…

我的组件代码是这样的:



  
{{ message }}
import { ref } from 'vue' export default { setup() { const message = ref('Hello') return { message } } }

已经安装了@babel/preset-typescript并添加到babel.config.js,但重启Vite后问题依旧。尝试过把.ts文件改为.js但.vue文件里lang=”ts”应该没问题吧?

我来解答 赞 11 收藏
二维码
手机扫码查看
2 条解答
Des.斯羽
你这个情况我也遇到过,其实问题出在两个地方。首先你说用了@babel/preset-typescript,但Babel对Vue单文件组件的处理本身是有局限的。特别是Vite默认用的是原生的TypeScript支持,而不是Babel来处理.ts文件。

你那个错误提示看起来像是JSON解析错误,这说明你的配置可能并没有真正启用TypeScript支持。

**第一步:确认是否安装了必要的依赖**

除了 @babel/preset-typescript,你还应该安装:

npm install --save-dev typescript @vitejs/plugin-vue


因为Vite默认用的是原生TypeScript支持,你还得加一个配置文件:

创建 tsconfig.json

{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": false,
"outDir": "./dist",
"esModuleInterop": true,
"skipLibCheck": true,
"lib": ["esnext", "dom"],
"types": ["vite/client"]
},
"include": ["./src/**/*"]
}


**第二步:确认你的Vue文件是否写法正确**

你给的组件代码看起来像是用了