Javascript 如何使用Vue在单个文件组件中使用类型脚本?

Javascript 如何使用Vue在单个文件组件中使用类型脚本?,javascript,laravel,typescript,vue.js,Javascript,Laravel,Typescript,Vue.js,我试图在Vue SFC中使用TypeScript的优点 安装ts加载程序,typescript依赖项 我添加了tsconfig.json配置 // tsconfig.json { "compilerOptions": { // this aligns with Vue's browser support "target": "es5", // this enables stricter inference for data properties on

我试图在Vue SFC中使用TypeScript的优点

安装
ts加载程序
typescript
依赖项

我添加了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});
        }

    },
....

从“Vue”导入Vue;
从“vuex”导入{mapState,mapGetters}
导出默认Vue.extend({
数据(){
返回{
编号:0
}
},
方法:{
//错误无效
upCount():void{
这个.store.commit('increment');
},
downCount():void{
这个.store.commit('decreation');
},
upCountBy():void{
this.$store.commit('incrementBy',{count:this.number});
}
},
....
错误

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


我将VueJs与Laravel和Laravel Mix base安装的WebPack一起使用。我如何解决这个问题?

当我开始使用Vue和TypeScript时,我遇到了类似的问题,我花了很长时间才使其正常工作。请尝试将其添加到
WebPack.config.js

。。。
模块:{
规则:[
{
测试:/\.tsx?$/,,
使用:[{
加载器:“ts加载器”,
选项:{
附录后缀:[/\.vue$/]
}
}],
排除:/node\u模块/
},
//确保vue加载程序位于ts加载程序之后
{
测试:/\.vue$/,,
加载程序:“vue加载程序”
},
...

尝试翻转康纳姆建议答案的顺序

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

为我工作。你安装了vue加载程序

npm i -D ts-loader typescript vue-loader

示例中的哪一行与错误消息中的第45行相对应?@Connum是的,它在代码中被注释,返回类型void或任何返回将其标记为errorYes,我添加了您的答案,但它仍然显示相同的错误您是否重新启动了webpack dev服务器?因为当您更改webpack配置时,它们不会自动进行更改像热模块重新加载一样重新加载。这是经常发生在我身上的事情。;-)是的,重新启动,错误仍然存在。我使用的是laravel mix,这可能是一个细节吗?我自己对lavarel不太熟悉,但这不应该有什么区别,因为这是所有将在客户端执行的资产,而不是任何php代码。如果您在问题中发布您的网页配置文件,可能会有所帮助。