Typescript 在 d.ts 中動態聲明命名導出
P粉642436282
P粉642436282 2024-02-26 11:58:58
0
1
386

我在TypeScript 中為VueJs 製作了一個元件庫,我希望能夠在我的Vue 實例中全域使用它們(使用Vue.use(library))或一一使用它們(使用Vue元件中的命名導入)

它運作得很好,但是當我想動態地聲明index.d.ts 檔案中的所有元件時,我在使用TypeScript 時遇到一些問題(因為元件很多,我不想手動執行)

所以這是有效的:

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

但它不起作用,當我執行 import { Component1 } from 'my-library' 時出現 TS 錯誤:

“無法解析符號“Component1” TS2614:模組「my-library」沒有匯出成員「Component1」。您是否打算使用「從「my-library」匯入 Component1」? ”

ps:如果我在導入之前使用 //@ts-ignore ,一切都會正常。

有什麼想法嗎?

P粉642436282
P粉642436282

全部回覆(1)
P粉739886290

我的猜測是,這是因為 TS 在建置時需要一些東西來進行「類型檢查」。換句話說,TS 比 JS 更具限制性,這是失去靈活性的主要範例之一,因為它希望在建置時而不是運行時進行定義。

簡而言之,你不能這麼做。您唯一能做的就是匯出鍵控物件中的所有內容,但這表示當您將其匯入另一個檔案時,您必須取得整個內容而不能取得其中的一部分。

檔.vue



熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!