首页 > 解决方案 > Typescript 在 d.ts 中动态声明命名导出

问题描述

我在 TypeScript 中为 VueJs 制作了一个组件库,我希望能够在我的 Vue 实例中全局使用它们(使用Vue.use(library))或一个接一个地使用它们(在 Vue 组件中使用命名导入)

它工作正常,但是当我想动态地声明文件中的所有组件时,我在使用 TypeScript 时遇到了一些问题index.d.ts(因为有很多组件,我不想手动进行)

所以这是有效的:

import { Component1, Component2 } from 'my-library';

declare module 'my-library' {
  declare const lib: PluginFunction<any>;
  export default lib;

  export { Component1, Component2 } from 'my-library';
}

但是我正在寻找一种方法来为所有组件执行此操作,而无需逐个导入和导出它们。

我试过这样的事情:

...
export * from 'my-library'
...

或者

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 };
  })
}

但它不起作用,当我这样做时出现 TS 错误import { Component1 } from 'my-library'

“无法解析符号 'Component1' TS2614:模块 ''my-library'' 没有导出的成员 'Component1'。您的意思是改用 'import Component1 from “my-library”' 吗?”

//@ts-ignoreps:如果我在导入前使用 a 一切正常。

任何想法?

标签: javascripttypescriptvue.js.d.ts

解决方案


推荐阅读