繁体   English   中英

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没有检测到此错误; 当我使用TypeScript加载程序运行Webpack时,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名称中可以ui-kit-libary-in-development ,这还不是npm-dependency,因此它现在不在node_modules内部。

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

  • SimpleCheckbox.vueSkipProjectInitializationStepPanel.ts移至同一目录,并将其作为import SimpleCheckbox from './SimpleCheckbox.vue';
  • @Component({ template, components: { SimpleCheckbox } })删除SimpleCheckbox并仅保留@Component({ template, components: {} }) (当然,在这种情况下,将不会呈现SimpleCheckbox ,但事实证明该问题是不在SkipProjectInitializationStepPanel )。
  • ui-kit-libary-in-development node_modules主项目的node_modules ,并从ui-kit-libary-in-development删除node_modules (如果不删除,则不会有任何变化)。

不幸的是,我无法重现此问题。 由于某些原因,下面的重试效果没有错误:

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.pug

.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>

我发现的所有线索都是该问题的注释, 在组件装饰器中设置组件会导致Typescript 2.4错误

侧面组件应添加.d.ts才能正常运行。

尼克·梅辛

从这个线索中,产生了以下问题:

  • 在我的主项目或依赖项中应在哪里创建.d.ts 最有可能在主项目中,但是如果是这样,为什么我可以在vuetify类的第三方库中导入辅助组件? 因为那里有.d.ts
  • 我如何需要在.d.ts声明新的Vue组件? 一些教程或示例?

赏金源文件

因为我无法重现此问题,并且我的项目仍然是原始项目(尚未获得商业价值),所以我可以通过Google云端硬盘( 下载zip存档的链接)进行共享。 所有的node_modules都包括在内,只需在main-project目录中运行npm run developmentBuild

如果您担心潜在的病毒,也可以在此存储库中获取源文件,但是由于它不包含node_modules ,因此,要进行复制,需要在main-projectdependency目录中执行npm install

这已经是一个很长的答案。 如果您没有时间阅读所有内容,请在末尾找到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>的错误消息。

注意:在最新版本(3.6.3)中,TypeScript实际上会显示一个更好的错误,说明重载和不匹配的原因。

更好的错误信息

我要做的下一件事是暂时注释掉main-project/node_modules/vue-class-component的第二个函数声明,并确保我们得到了不同的错误消息。 新消息跨越63行,因此我认为将其作为一个整体包含在这篇文章中是没有意义的。

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 {}

当使用npm run webpackmain-project运行此示例时,我们得到与以前完全相同的错误。 任务完成。

发生了什么?

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

您可能已经注意到我已添加到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感兴趣。 该评论实际上已经给了我们提示: 扩充Vue.js的类型

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

import { Store } from "./index";

// ...

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

这是罪魁祸首。 vuex类型利用声明合并$store添加到vueVue接口。 看来,这增强只发生在同一个“本地”类型node_modulesvuex 因为main-project具有增强的Vuedependency具有原始Vue ,所以两者不匹配。

TS装载机

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

解决方法

我有一些想法可以解决或解决此问题。 尽管这些不一定是立即可用的解决方案,而是不同的方法和想法。

vuex添加到dependency

因为从main-project删除vuex并不是一个真正的选择,所以我们要做的唯一一个使两个Vue接口都匹配的方法就是将vuex也包含在dependency中。

奇怪的是,我能够在最小的示例中获得此修复程序,但在原始项目中却没有。 我还不知道为什么。

除此之外,它还不是很优雅,您可能必须从main-project引用的每个文件中导入vuex

使用共享的node_modules

具有共享node_modules文件夹的手段这两个项目使用相同的vue所以这个问题消失。 根据您的要求,将两个项目共享一个相同的node_modules文件夹来组织它们可能是一个很好的解决方案。 您可能还想看一下LernaYarn工作区之类的工具,它们可以为您提供帮助。

dependency作为包使用

您说dependency 不是npm-dependency 也许是时候做到这一点了。 与共享的node_modules目录类似,这将导致两个项目使用相同的vue安装,这将解决此问题。

进一步调查

如前所述,这仅在ts-loader发生。 也许可以在ts-loader固定或配置某些东西来避免此问题。

TL; DR

main-project导入vuex而没有dependency vuex使用声明合并来增强Vue接口, 并在其中添加$store属性。 现在Vue从一个项目不匹配Vue其他导致错误。

正如@lukasgeiter所说,

显然ts-loader所做的事情有所不同,导致了此问题。

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

暂无
暂无

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

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