vue3的.vue文件怎么配置才能支持typescript代码

vue3 + webpack4,vscode代码编译没有报错,但是npm run dev的时候报了如下错误:
看上去是typescript和vue-loader没配置好,用的是@babel/preset-typescript,没用ts-loader,请问大神们怎么解决呢?

ERROR in ./src/components/dialog/dialog.vue?vue&type=script&lang=ts (./node_modules/babel-loader/lib!./node_modules/vue-loader/dist??ref--19-0!./src/components/dialog/dialog.vue?vue&type=script&lang=ts)
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: D:\workspace\VueBootstrap\src\components\dialog\dialog.vue: Missing semicolon. (6:12)

 export default defineComponent({
  5 |   setup() {
> 6 |     let test: boolean = false;
    |             ^
  7 |   },
  8 | })

dialog.vue代码

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  setup() {
    let test: boolean = false;
  },
})
</script>

package.json中的devDependencies

{
  "devDependencies": {
    "@babel/core": "^7.14.6",
    "@babel/plugin-proposal-class-properties": "^7.14.5",
    "@babel/plugin-proposal-object-rest-spread": "^7.14.5",
    "@babel/plugin-transform-runtime": "^7.14.5",
    "@babel/preset-env": "^7.14.5",
    "@babel/preset-typescript": "^7.14.5",
    "@vue/compiler-sfc": "^3.1.1",
    "babel-loader": "^8.1.0",
    "clean-webpack-plugin": "^3.0.0",
    "copy-webpack-plugin": "^6.0.3",
    "css-loader": "^4.2.1",
    "file-loader": "^6.0.0",
    "html-loader": "^1.2.1",
    "html-webpack-exclude-assets-plugin": "0.0.7",
    "html-webpack-plugin": "^4.5.2",
    "html-webpack-skip-assets-plugin": "0.0.2",
    "mini-css-extract-plugin": "^0.10.0",
    "source-map-loader": "^2.0.2",
    "style-loader": "^1.2.1",
    "terser-webpack-plugin": "^5.1.3",
    "typescript": "^4.3.4",
    "url-loader": "^4.1.0",
    "vue-loader": "^16.1.2",
    "webpack": "^4.44.2",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  }
}

.babelrc

{
    "presets": [
        "@babel/env",
        "@babel/typescript"
    ],
    "plugins": [
        "@babel/transform-runtime",
        "@babel/proposal-class-properties",
        "@babel/proposal-object-rest-spread"
    ]
}

webpack配置

rules: [
//.....
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      },
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      },
      {
        test: /\.vue$/,
        use: ['vue-loader']
      }
//......
]
阅读 4k
1 个回答

找到解决方法了,@babel/typescript加入配置项allExtensions: true,具体如下

{
    "presets": [
        "@babel/env",
        [
            "@babel/typescript",
            {
                "allExtensions": true
            }
        ]
    ],
    "plugins": [
        "@babel/transform-runtime",
        "@babel/proposal-class-properties",
        "@babel/proposal-object-rest-spread"
    ]
}

原理:.vue文件需要通过vue-loader中转到babel,但是默认的babel配置不会处理.vue文件,所以要有上面的配置

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题