I made a library of components for VueJs in TypeScript and I want to be able to use them globally in my Vue instance (with Vue.use(library)) or one by one (with named import in Vue compoenent)
It works fine, but I have some issues with TypeScript for declaring all the components in index.d.ts file when I want to do it dynamically (because there are many components and I don't want to do it manually)
So this is working :
import { Component1, Component2 } from 'my-library';
declare module 'my-library' {
declare const lib: PluginFunction<any>;
export default lib;
export { Component1, Component2 } from 'my-library';
}
But I'm looking for a way to do this for all the components without importing and exporting them one by one.
I tried something like this :
...
export * from 'my-library'
...
or
import * as components from 'my-library';
declare module 'my-library' {
declare const lib: PluginFunction<any>;
export default lib;
Object.entries(components).forEach(([componentName, component]) => {
export { component as componentName };
// or
// export { component };
})
}
But it doesn't work, I got TS errors when I do import { Component1 } from 'my-library':
"Cannot resolve symbol 'Component1' TS2614: Module '"my-library"' has no exported member 'Component1'. Did you mean to use 'import Component1 from "my-library"' instead?"
ps: everything works fine if I use a //@ts-ignore before the import.
Any idea?
My guess is this is because TS requires things at build time to do its "typeschecking" stuff. In other words, TS is more restrictive than JS and this is one of the prime examples where you lose flexibility because it wants to have definitions at build time rather than runtime.
So in short, you can't do this. The only thing you can do it is export everything in an key'ed object, but that means when you import it in another file you have to take the whole thing and can't take part of it.
File.vue
<CustomNamedThing/>
<script>
import Foo from './yourfile.ts'
components: {
CustomNamedThing: Foo.CustomNamedThing
}, ...
</script>