如何通过Vue在单个文件组件中使用TypeScript?

时间:2019-04-05 16:12:38

标签: javascript laravel typescript vue.js

我正在尝试在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});
        }

    },
....

错误

  

模块解析失败:意外的令牌(45:12)您可能需要一个   适当的加载程序来处理此文件类型。

我正在使用VueJ和Laravel和Laravel Mix基本安装中的WebPack。我该如何解决?

2 个答案:

答案 0 :(得分:1)

当我开始使用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'
        },
...

答案 1 :(得分:0)

尝试并翻转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