简体   繁体   English

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

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

I'm trying to use the TypeScript benefits in a Vue SFC, 我正在尝试在Vue SFC中使用TypeScript的优势,

Install the ts-loader , typescript dependencies 安装ts-loadertypescript依赖

I added the tsconfig.json configuration 我添加了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"
    }

} }

But when trying to compile the next component it shows me error. 但是,当尝试编译下一个组件时,它向我显示错误。

<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});
        }

    },
....

the error 错误

Module parse failed: Unexpected token (45:12) You may need an appropriate loader to handle this file type. 模块解析失败:意外的令牌(45:12)您可能需要适当的加载程序来处理此文件类型。

I am using VueJs together with WebPack from a Laravel and Laravel Mix base installation. 我在Laravel和Laravel Mix基本安装中将VueJ和WebPack一起使用。 How do I solve this? 我该如何解决?

When I started using Vue and TypeScript, I ran into similiar problems at first and it took me quite a while to get it to work. 当我开始使用Vue和TypeScript时,最初遇到了类似的问题,并且花了我相当长的时间才能使它工作。 Try adding this to your webpack.config.js 尝试将其添加到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'
        },
...

Try and flip the order of Connum's suggested answer. 尝试颠倒Connum建议答案的顺序。

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

Worked for me. 为我工作。 You have installed the vue-loader? 您已经安装了vue-loader?

npm i -D ts-loader typescript vue-loader

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM