如何在Vue的单文件组件中使用TypeScript的那种?

How to use the kind of TypeScript in a Single File Component with Vue?

我正在尝试在 Vue SFC 中使用 TypeScript 的好处,

安装 ts-loadertypescript 依赖项

我添加了tsconfig.json配置

// tsconfig.json
{
    "compilerOptions": {
      // this aligns with Vue's browser support
      "target": "es5",
      // this enables stricter inference for data properties on `this`
      "strict": true,
      // if using webpack 2+ or rollup, to leverage tree shaking:
      "module": "es2015",
      "moduleResolution": "node"
    }

}

但是当我尝试编译下一个组件时它显示错误。

<script lang="ts">
import Vue from "vue";
import { mapState,mapGetters } from 'vuex'


export default Vue.extend({
    data() {
        return {
            number : 0
        }
    },
    methods:{
        // error void
        upCount() : void {
            this.$store.commit('increment');
        },
        downCount() : void{
            this.$store.commit('decrement');
        },
        upCountBy() : void {
            this.$store.commit('incrementBy',{count : this.number});
        }

    },
....

错误

Module parse failed: Unexpected token (45:12) You may need an appropriate loader to handle this file type.

我在 Laravel 和 Laravel Mix 基础安装中将 VueJs 与 WebPack 一起使用。我该如何解决?

当我开始使用 Vue 和 TypeScript 时,一开始我 运行 遇到了类似的问题,我花了很长时间才让它开始工作。尝试将此添加到您的 webpack.config.js

...
    module: {
      rules: [
        {
          test: /\.tsx?$/,
          use: [{
            loader: 'ts-loader',
            options: {
              appendTsSuffixTo: [ /\.vue$/ ]
            }
          }],
          exclude: /node_modules/
        },
        // make sure vue-loader comes after ts-loader
        {
          test: /\.vue$/,
          loader: 'vue-loader'
        },
...

尝试翻转 Connum 建议答案的顺序。

module: {
      rules: [
                {
                    test: /\.vue$/,
                    use: 'vue-loader',
                },
                {
                    test: /\.ts$/,
                    exclude: /node_modules/,
                    use: [{ loader: 'ts-loader', options: { appendTsSuffixTo: [/\.vue$/] } }],
                },
              ]
}

对我有用。你已经安装了vue-loader?

npm i -D ts-loader typescript vue-loader