【问题标题】:Vite build and Global Vue 3 Components via Typescript通过 Typescript 构建 Vite 和 Global Vue 3 组件
【发布时间】:2021-06-24 11:44:36
【问题描述】:

可以通过修复 typescript 错误或如何最好地使用 Typescript 处理全局 Vue 3 组件注册来回答这个问题。简而言之,如果我运行npm run dev (vite),开发服务器运行良好并且没有问题。尝试通过npm run build (vue-tsc --noEmit && vite build) 生成构建时,会出现以下错误:

src/main.ts:15:17 - 错误 TS1131:需要属性或签名。

15 app.component(Components[key].name, Components[key]);

一点背景知识,我所拥有的所有组件都是基于documentationdefineComponent 的使用创建的。下面是一个例子。在某些时候,需要全局注册多个组件,因为它们会在整个应用程序中使用。

<script lang="ts">
//sbutton.vue
import { defineComponent } from "vue";

export default defineComponent({
  name: "s-button",
  props: {
    disabled: {
      default: false,
      type: Boolean
    },
    loading: {
      default: false,
      type: Boolean
    }
  },
  computed:{
    disableBtn(): Boolean {
      return this.loading || this.disabled;
    }
  }
});
</script>

我采用了全局组件并将它们合并为一个我可以在全局运行和注册的对象。

// components/index.ts

import BlogSubscribe from './BlogSubscribe.vue';
import SButton from './SButton.vue';

const components = {
    BlogSubscribe,
    SButton
};

export default components;

最后在 main.ts 中全局注册:

import Components from './components';

const app = createApp(App).use(router);

for (const key in Components) {
  app.component(Components[key].name, Components[key]);  // <- error here
}

回顾一下,使用 vue3、vite、typescript 注册一组全局组件以生成应用程序的构建版本的最佳过程是什么。

【问题讨论】:

    标签: typescript vue-component vuejs3 vite


    【解决方案1】:

    我以这种方式解决了这个问题,但不确定这是使用 vite/vue3 处理全局 vue 组件注册的最佳方式,也不推荐使用。

    const components:{[index:string]: Component<any, any, any, ComputedOptions, MethodOptions>} = {
       [BlogSubscribe.name]: BlogSubscribe,
        [SButton.name]: SButton
    };
    
    export default components;
    

    在 main.ts 中:

    for (const key in Components) {
      app.component(key, Components[key]);
    }
    

    【讨论】:

      【解决方案2】:

      我通过删除 vue-tsc --noEmit &amp;&amp; 来解决这个问题

      【讨论】:

        猜你喜欢
        • 2022-12-28
        • 2021-10-30
        • 2023-01-30
        • 2022-01-16
        • 2022-06-10
        • 1970-01-01
        • 2022-07-06
        • 2021-08-20
        • 2022-10-14
        相关资源
        最近更新 更多