Currently, I am in the process of developing a Vue 3 component library using Vue 3, Vite, and TypeScript. The unique aspect about this library is that it installs as a plugin and registers all components as global entities. Here is an overview of how this process looks:
// 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 */ };
In order to build this library, I utilize Vite's Library Mode, which involves the following configuration:
// 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 || {})],
},
},
});
Furthermore, the build command I use for this project includes the following steps:
vite build && vue-tsc --emitDeclarationOnly && mv dist/src dist/types
This generates a dist
directory containing a .d.ts
file for each individual component. Despite being able to successfully import the library into various projects, unfortunately, TypeScript support is lacking for the global components.
In my search for a solution, I came across a helpful post on Stack Overflow that suggests adding globals through augmentation:
// src/global-components.d.ts
import Component1 from "@/components/Component1.vue";
declare module "@vue/runtime-core" {
export interface GlobalComponents {
Component1: typeof Component1;
}
}
Although I attempted adding a similar file directly to the library, it did not yield the desired outcome. As a workaround, I included a comparable file in the project and imported each Vue component .d.ts
file from the library's dist/types/*
directory to provide TypeScript support within the project. While this method works, ideally, I would prefer this functionality to be intrinsic to the library itself.
With that context in mind, my primary question is regarding the implementation of TypeScript support for global components in my library, ensuring its availability to projects utilizing it. If additional details are necessary, please feel free to request them.