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

黑暗凤凰

我正在尝试在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)您可能需要适当的加载程序来处理此文件类型。

我将VueJs与Laravel和Laravel Mix基本安装中的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'
        },
...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章