【问题标题】:How to use the kind of TypeScript in a Single File Component with Vue?如何在带有 Vue 的单个文件组件中使用那种 TypeScript?
【发布时间】:2019-08-27 14:28:23
【问题描述】:

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

我正在使用来自 Laravel 和 Laravel Mix 基础安装的 VueJs 和 WebPack。我该如何解决?

【问题讨论】:

  • 示例中的哪一行与错误消息中的第 45 行相对应?
  • @Connum 是的,代码里有注释,返回void类型或者任何return都标记为错误

标签: javascript laravel typescript vue.js


【解决方案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'
        },
...

【讨论】:

  • 是的,我添加了您的答案,但仍然显示相同的错误
  • 你重启了 webpack-dev-server 了吗?因为当您对 webpack 配置进行更改时,它们不会像热模块重新加载那样自动重新加载。这是我经常发生的事情。 ;-)
  • 是的,重新启动,错误仍然存​​在。我正在使用 laravel mix,可以详细说明一下吗?
  • 我自己对 lavarel 并不熟悉,但它不应该真正产生影响,因为这完全是关于将在客户端执行的资产,而不是任何 php 代码。如果您也在问题中发布了您的 webpack 配置文件,这可能会有所帮助。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 2020-01-18
    • 2023-03-20
    • 1970-01-01
    • 2020-05-29
    • 2021-12-19
    • 2017-05-29
    • 2018-06-10
    • 2019-03-06
    相关资源
    最近更新 更多