
[英]Automatically import Typescript namespace from namespace/type only NPM module in mono-repo
[英]How can I make VS Code recognize typescript declarations between mono-repo packages?
我有一個單存儲庫項目,配置了一個隔離庫 package(僅限 TS)和另一個 web UI package(TS + React)。
我正在從消費者(Web UI)package 導入已編譯的庫 package。 為此,我使用 yarn 來鏈接包和 parcel 以生成庫包的分發文件。
Parcel 會在庫包的dist
文件夾中自動生成一個d.ts
文件。
我正在使用 VS Code 作為 IDE 並且當我打開導入庫並使用它的消費者包文件時,VS Code 無法識別庫包的d.ts
文件中聲明的類型。
這是包的結構:
rootPackage
|- library
|- web-ui
在library
package 中,我有一個types.ts
文件和一個index.ts
文件。 只有一種類型被導出:
export type ParamType = "a" | "b" | "c";
我在這個 package 上使用parcel watch
來在發生更改時自動刷新dist
文件。
Parcel 正在生成main.d.ts
文件,並且該文件被package.json
的types
屬性引用。
當我嘗試通過web-ui
包的代碼使用此ParamType
類型時,我在類型中突出顯示以下 IDE 錯誤:
Cannot find name 'ParamType'.ts(2304)
當我在web-ui
package 中運行 parcel 時,它編譯得很好,並且瀏覽器加載沒有問題/警告。
我認為這是一個與 VS Code 相關的問題,我不知道如何解決它。
我在 GitHub 上創建了一個公共存儲庫來演示該問題。 如果您知道如何修復它,請隨時創建拉取請求,這將非常有幫助。
從您的示例 repo中,您的library
package 的根如下所示:
/shared/lib/src/index.ts
import { ParamType } from "./types";
const Library = {
typedParamMethod(param: ParamType) {
console.log(param);
},
};
export default Library;
您在web-ui
package 中使用library
package 的方式是這樣的:
/ui/web/src/App.tsx
import React from 'react';
import Library from 'library';
function App() {
React.useEffect(() => {
const typedParam: ParamType = 'b'; // VSCode and tsc throw the error "Cannot find name 'ParamType'."
Library.typedParamMethod(typedParam);
}, []);
return (
<div className="web-ui">Web UI</div>
);
}
export default App;
問題是您既沒有將ParamType
從library
package 的根目錄導出,也沒有將其導入您的web-ui
package。 Modern JavaScript and Typescript modules are isolated from each other - the import { ParamType } from "./types"
line in your library
package root makes ParamType
available in that file , but it doesn't affect (or pollute) the global namespace of something這恰好從library
package 中導入其他內容(例如默認導出)。
為了解決這個問題,將此行添加到library
package 根目錄(例如/shared/lib/src/index.ts
):
export { ParamType } from "./types.ts";
然后從您的web-ui
package (在/ui/web/src/App.tsx
中)修改導入:
import Library, { ParamType } from 'library';
(問題和解決方案與 VSCode 無關——任何嘗試對web-ui
package 進行類型檢查的東西都會發出相同的錯誤,沒有這些更改)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.