Vue&TypeScript:在项目目录外的 TypeScript 组件中实现导入时如何避免错误 TS2345?

Vue&TypeScript: how to avoid error TS2345 when import implemented in TypeScript component outside of project directory?

我在尝试使用辅助组件(在项目目录之外)时出现以下 TypeScript 错误:

TS2345: Argument of type '{ template: string; components: { SimpleCheckbox: typeof SimpleCheckbox; }; }' 
is not assignable to parameter of type 'VueClass<Vue>'.
Object literal may only specify known properties, and 'template' does not exist in type 
'VueClass<Vue>'.

我的 WebStorm IDE 没有检测到这个错误;当我 运行 Webpack with TypeScript loader.

时在控制台中输出 in

错误发生在:

import { Vue, Component, Prop } from 'vue-property-decorator';
import template from './SkipProjectInitializationStepPanel.pug';
import SimpleCheckbox from './../../../../ui-kit-libary-in-development/UiComponents/Checkboxes/MaterialDesign/SimpleCheckbox.vue';


@Component({ template, components: { SimpleCheckbox } }) // here !
export default class SkipProjectInitializationStepPanel extends Vue {
  @Prop({ type: String, required: true }) private readonly text!: string;
}

ui-kit-libary-in-development name 可以看出,这还不是 npm-dependency,所以暂时不在 node_modules 中。

完全是TypeScript错误;尽管 ts-loader 抛出了这个错误,Webpack 构建了我的项目并编译 JavaScript 正常工作。如果执行以下操作之一,此错误将消失:

不幸的是,我无法重现这个问题。由于某些原因,下面尝试无错误地复制作品:

MainProject/src/Application.vue

<template lang="pug">
  PageOne
</template>

<script lang="ts">
  import { Vue, Component } from 'vue-property-decorator';
  import PageOne from './PageComponents/PageOne'

  @Component({ components: { PageOne }})
  export default class Application extends Vue {
    private created(): void {
      console.log('Done.');
    }
  }
</script>

MainProject/src/PageComponents/PageOne.ts

import { Vue, Component, Prop } from 'vue-property-decorator';
import template from './PageOne.pug';
import Button from './../../../UiKitLibraryStillInDevelopment/UiComponents/Buttons/Button.vue';


@Component({ template, components: { Button } })
export default class SkipProjectInitializationStepPanel extends Vue {}

MainProject/src/PageComponents/PageOne.哈巴狗

.RootElement
  Button(:text="'Click me'")

ui-kit-libary-in-development/UiComponents/Buttons/Button.vue

<template lang="pug">
  button {{ text }}
</template>


<script lang="ts">
  import { Vue, Component, Prop } from 'vue-property-decorator';

  @Component
  export default class SimpleCheckbox extends Vue {
    @Prop({ type: String, required: true }) private readonly text!: string;

    private created(): void {
      console.log('OK!');
      console.log(this.$props);
    }
  }
</script>

我发现的所有线索都是问题 Setting components in Component decorator causes Typescript 2.4 error 中的评论:

Side components should add .d.ts for it to work AFAIK.

Nick Messing

由此线索,产生以下问题:


赏金源文件

因为我无法重现这个问题,而且我的项目还是原始的(还没有商业价值),我可以通过Google驱动(link for downloading zip archive)分享它。所有 node_modules 都包括在内,只是 main-project 目录中的 运行 npm run developmentBuild

如果你担心潜在病毒,你也可以在this repository中获取源文件,但是因为它不包含node_modules,为了复制它需要执行npm installmain-projectdependency 目录中。

这已经变得很长了。如果您没有时间阅读所有内容,最后会有 TL;DR.


分析

错误信息

起初我不太明白为什么 TypeScript 提到 VueClass<Vue> 并抱怨 template 属性。但是,当我查看 Component 装饰器的类型定义时,事情变得更清楚了:

vue-class-component/lib/index.d.ts(部分省略)

declare function Component<V extends Vue>(options: ComponentOptions<V> & ThisType<V>): <VC extends VueClass<V>>(target: VC) => VC;
// ...
declare function Component<VC extends VueClass<Vue>>(target: VC): VC;

我们在这里可以看到Component有两个签名。第一个像你一样使用,第二个没有选项(@Component class Foo)。

显然编译器认为我们的用法与第一个签名不匹配,所以它必须是第二个。因此,我们最终得到一条带有 VueClass<Vue>.

的错误消息

Note: In the latest version (3.6.3), TypeScript will actually display a better error, stating both overloads and why they don't match.

更好的错误消息

接下来我做的是暂时注释掉 main-project/node_modules/vue-class-component 中的第二个函数声明,果然我们得到了不同的错误消息。新消息跨越 63 行,所以我认为将它作为一个整体包含在 post 中是没有意义的。

ERROR in /tmp/main-project/InitializeProjectGUI__assets/SingletonComponents/SkipProjectInitializationStepPanel/SkipProjectInitializationStepPanel.ts
../InitializeProjectGUI__assets/SingletonComponents/SkipProjectInitializationStepPanel/SkipProjectInitializationStepPanel.ts
[tsl] ERROR in /tmp/main-project/InitializeProjectGUI__assets/SingletonComponents/SkipProjectInitializationStepPanel/SkipProjectInitializationStepPanel.ts(10,24)
      TS2322: Type '{ SimpleCheckbox: typeof SimpleCheckbox; }' is not assignable to type '{ [key: string]: VueConstructor<Vue> | FunctionalComponentOptions<any, PropsDefinition<any>> | ComponentOptions<never, any, any, any, any, Record<string, any>> | AsyncComponentPromise<any, any, any, any> | AsyncComponentFactory<...>; }'.
  Property 'SimpleCheckbox' is incompatible with index signature.
    Type 'typeof SimpleCheckbox' is not assignable to type 'VueConstructor<Vue> | FunctionalComponentOptions<any, PropsDefinition<any>> | ComponentOptions<never, any, any, any, any, Record<string, any>> | AsyncComponentPromise<any, any, any, any> | AsyncComponentFactory<...>'.
      Type 'typeof SimpleCheckbox' is not assignable to type 'VueConstructor<Vue>'.
        Types of property 'extend' are incompatible.
          Type '{ <Data, Methods, Computed, PropNames extends string = never>(options?: import("/tmp/dependency/node_modules/vue/types/options").ThisTypedComponentOptionsWithArrayProps<import("/tmp/depende...' is not assignable to type '{ <Data, Methods, Computed, PropNames extends string = never>(options?: import("/tmp/main-project/node_modules/vue/types/options").ThisTypedComponentOptionsWithArrayProps<import("/tmp/main-...'.
            ...
              Type 'import("/tmp/dependency/node_modules/vue/types/vnode").ScopedSlotReturnValue' is not assignable to type 'import("/tmp/main-project/node_modules/vue/types/vnode").ScopedSlotReturnValue'.
                Type 'VNode' is not assignable to type 'ScopedSlotReturnValue'.

如您所见,错误消息很难读懂,并且没有真正指出具体问题。因此,我继续前进并开始降低项目的复杂性,以便更好地理解问题。

最小示例

我将为您省去涉及大量试验和错误的整个过程。让我们直接跳到结果。

结构

├─ main-project
│  ├─ node_modules // installed packages listed below (without sub-dependencies)
│  │     ts-loader@6.1.0
│  │     typescript@3.6.3
│  │     vue@2.6.10
│  │     vue-property-decorator@8.2.2
│  │     vuex@3.1.1
│  │     webpack@4.40.2
│  │     webpack-cli@3.3.9
│  ├─ SkipProjectInitializationStepPanel.ts
│  ├─ tsconfig.json
│  └─ webpack.config.js
└─ dependency
   ├─ node_modules // installed packages listed below (without sub-dependencies)
   │     vue@2.6.10
   └─ SimpleCheckbox.ts

main-project/tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "strict": true,
    "moduleResolution": "node"
  }
}

main-project/webpack.config.js:

module.exports = {
    entry: './SkipProjectInitializationStepPanel.ts',
    mode: 'development',
    module: {
        rules: [
            {
                test: /\.ts$/,
                loader: 'ts-loader'
            }
        ]
    },
    resolve: {
        extensions: ['.ts', '.js']
    }
};

main-project/SkipProjectInitializationStepPanel.ts:

import { Component } from 'vue-property-decorator';
import 'vuex';

import SimpleCheckbox from '../dependency/SimpleCheckbox';

Component({ template: '', components: { SimpleCheckbox } });

dependency/SimpleCheckbox.ts:

import Vue from 'vue';

export default class SimpleCheckbox extends Vue {}

当 运行 来自 main-project 的示例与 npm run webpack 时,我们得到与之前完全相同的错误。任务完成。

发生了什么事?

当我删除部分项目以将其简化为这个最小示例时,我学到了一些非常有趣的东西。

您可能已经注意到我添加到 SkipProjectInitializationStepPanel.tsimport 'vuex'。在原始项目中,vuex 当然是从不同的地方导入的(例如 main-project/Source/ProjectInitializer/Store/Store.ts),但这对于重现问题并不重要。关键部分是 main-project 导入 vuexdependency 不导入 .

要找出导入 vuex 导致此问题的原因,我们必须查看 vuex.

的类型定义

vuex/types/index.d.ts(前几行)

import _Vue, { WatchOptions } from "vue";

// augment typings of Vue.js
import "./vue";

import { mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers } from "./helpers";

这里我们对第二个感兴趣import。该评论实际上已经给了我们一个提示:augment typings of Vue.js.

vuex/types/vue.d.ts(部分省略)

import { Store } from "./index";

// ...

declare module "vue/types/vue" {
  interface Vue {
    $store: Store<any>;
  }
}

罪魁祸首在这里。 vuex 类型利用 declaration merging$store 添加到 vueVue 接口。似乎这种增强只发生在与 vuex 相同的 node_modules 中的“本地”类型。因为 main-project 有增强的 Vuedependency 有原始的,所以两者不匹配。

TS 加载器

在我所有的测试过程中,我无法仅用 tsc 重现问题。显然 ts-loader 做了一些不同的事情导致了这个问题。它可能与使用 Webpack 进行模块解析有关,也可能是完全不同的东西。我不知道。

解决方法

我对如何解决或解决这个问题有一些想法。尽管这些不一定是现成的解决方案,而是不同的方法和想法。

vuex 添加到 dependency

由于从 main-project 中删除 vuex 并不是一个真正的选择,我们唯一能做的就是让 Vue 接口匹配,将 vuex 包含在dependency 还有。

奇怪的是,我能够在我的最小示例中修复此问题,但在原始项目中却没有。我还没弄明白为什么会这样。

除此之外,它不是很优雅,您可能必须从您从 main-project.

引用的每个文件中导入 vuex

使用共享 node_modules

拥有一个共享的 node_modules 文件夹意味着两个项目使用相同的 vue 所以这个问题就消失了。根据您的要求,以共享相同 node_modules 文件夹的方式组织两个项目可能是一个很好的解决方案。您可能还想看看像 Lerna or Yarn workspaces 这样的工具,它可以帮助解决这个问题。

作为一个包消费dependency

你说 dependency 还不是 [an] npm-dependency 。也许是时候把它变成一个了。类似于共享 node_modules 目录,这将导致两个项目使用相同的 vue 安装,这应该可以解决问题。

进一步调查

如前所述,这只发生在 ts-loader 上。 也许可以在ts-loader中修复或配置一些东西来避免这个问题。

TL;DR

main-project 导入 vuexdependency 不导入。 vuex 使用 declaration merging 添加 $store 属性 来扩充 Vue 界面。现在一个项目的 Vue 与另一个项目的 Vue 不匹配,导致错误。

正如@lukasgeiter 所说,

Apparently ts-loader does something differently causing this issue.

如果将类型检查过程委托给 fork-ts-checker-webpack-plugin,错误将消失。