技術浮浪貢

在 CommonJS module 中使用 ESM 型別

要在 CommonJS module 中使用 ESM 必須透過動態 import;但型別是編譯時期的資訊,一定要用靜態 import。透過宣告檔案(Declaration File)可以解決這個問題。

首先加一個 .d.ts 重新 export 你用到的 type:

1// type-wrapper.d.ts
2export type { SomeType } from 'some-esm-package';
3// ...

這樣你就可以如同使用其他 CommonJS 一樣 import 它;實際使用到物件/值的地方還是得需要 dynamic import:

1// your .ts source file
2import type { SomeType } from './type-wrapper'
3
4
5// ...
6    const module = await import('some-esm-package');
7    const { someValue } = module;
8// ...

#ESM #CommonJS #JavaScript #TypeScript

« 上一篇

下一篇 »

相關文章