具有全局组件和 TypeScript 支持的 Vue 3 库

问题描述 投票:0回答:1

我正在使用 Vue 3、Vite 和 TypeScript 构建 Vue 3 组件库。该库作为插件安装,并将所有组件注册为全局变量。看起来是这样的:

// src/index.ts
const globalComponents = import.meta.glob("./components/**/*.vue", {
  eager: true,
});

export default {
  install(app: App, options: Record<string, string>) {
    Object.entries(globalComponents).forEach(
      ([item, definition]: [string, any]) => {
        const componentName = item
          ?.split("/")
          ?.pop()
          ?.replace(/\.\w+$/, "");

        app.component(componentName, definition.default);
      }
    );
  },
};

export { /* other exports */ };

我使用Vite的库模式来构建库,如下所示:

// vite.config.ts
export default defineConfig({
  plugins: [vue()],
  build: {
    target: "esnext",
    lib: {
      formats: ["es"],
      entry: path.resolve(__dirname, "src/index.ts"),
      fileName: (format) => `bundle.${format}.js`,
    },
    rollupOptions: {
      external: [...Object.keys(pkg.dependencies || {})],
    },
  },
});

最后,我的构建命令如下:

vite build && vue-tsc --emitDeclarationOnly && mv dist/src dist/types

这将创建一个

dist
目录,其中包含每个组件的
.d.ts
文件。我能够将该库导入到其他项目中,并获得对除全局组件之外的所有内容的 TypeScript 支持。 我发现

this SO post

解释了可以使用增强来添加全局变量: // src/global-components.d.ts import Component1 from "@/components/Component1.vue"; declare module "@vue/runtime-core" { export interface GlobalComponents { Component1: typeof Component1; } }

我尝试向库中添加类似的文件,但没有效果。

我向项目中添加了一个类似的文件,并从库

.d.ts

中导入了每个 Vue 组件

dist/types/*
文件,以在项目中提供 TypeScript 支持。这可行,但我更希望这些信息直接来自图书馆。
所以,这就是我的问题。如何向我的库添加对全局组件的 TypeScript 支持,并使其可供使用它的项目使用?

我希望这是清楚的。如果需要更多信息,请告诉我。

typescript vue.js vuejs3 vite
1个回答
0
投票
SO答案

并面临着同样的问题。 解决方案是将 declare module '@vue/runtime-core' 替换为

declare module 'vue'

这是因为大多数应用程序不包含

@vue/runtime-core

,如
herehere所指出:

由于许多项目没有安装@vue/runtime-core(特别是pnpm项目),unplugin-vue-components生成的类型将不起作用。 Vue 项目确实安装了 vue,并且增强 vue 本身足以让类型与 Volar 一起使用。

这也是
vue官方文档

展示如何使用TypeScript注册Web组件的方式:

如果您正在开发应用程序或库,您可能需要对 Vue 组件进行类型检查,包括那些定义为自定义元素的组件。

自定义元素是使用原生 API 全局注册的,因此默认情况下它们在 Vue 模板中使用时不会进行类型推断。为了为注册为自定义元素的 Vue 组件提供类型支持,我们可以使用 Vue 模板和/或 JSX 中的 GlobalComponents 接口来注册全局组件类型:

import { defineCustomElement } from 'vue' // vue SFC import CounterSFC from './src/components/counter.ce.vue' // turn component into web components export const Counter = defineCustomElement(CounterSFC) // register global typings declare module 'vue' { export interface GlobalComponents { 'Counter': typeof Counter, } }
© www.soinside.com 2019 - 2024. All rights reserved.