我正在 TypeScript 中創建一個 SVG 圖示庫。到目前為止,SVGR 非常棒,但我需要的最后一部分是生成的型別,以允許傳遞title和ref捆綁組件。
再生產
我不確定看到哪些內容可能會有所幫助,因此我將包含一個 repo 和一些代碼示例。但是通過以下設定,svgr 正在從 SVG 匯入創建組件,但沒有生成任何型別。結果,每當我嘗試使用此包中的圖示時,都會警告我找不到它的宣告檔案。
POC 回購:https ://github.com/yuschick/icon-demo
src/index.ts
export { default as TestIcon } from "./svg/test.svg";
export { default as ArrowThinLeft } from './svg/arrow-thin-left.svg';
包.json
{
"module": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"scripts": {
"build": "node esbuild.config.js",
},
"devDependencies": {
"esbuild": "^0.14.39",
"esbuild-plugin-svgr": "^1.0.1",
"typescript": "^4.6.3"
}
}
esbuild.config.js
import esbuild from "esbuild";
import svgr from "esbuild-plugin-svgr";
esbuild.build({
bundle: true,
entryPoints: ["src/index.ts"],
external: ["react"],
format: "esm",
// minify: true,
outfile: "dist/index.js",
plugins: [svgr({ titleProp: true, ref: true, expandProps: false, typescript: true })],
})
.catch(() => process.exit(1));
tsconfig.json
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"alwaysStrict": true,
"baseUrl": "src",
"checkJs": true,
"declaration": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"lib": ["dom", "dom.iterable", "esnext"],
"module": "esnext",
"moduleResolution": "node",
"noEmit": true,
"outDir": "dist",
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"target": "esnext"
},
"include": ["src", "global.d.ts"]
}
全球.d.t??s
declare module '*.svg' {
const content: string;
export default content;
}
預期行為
通過傳入typescript: true選項svgr,我期望index.d.tsx根據生成的組件生成一個檔案。
根據 SVGR 檔案:
使用TypeScript型別生成 .tsx 檔案。
注意:雖然我在 ESBuild 中使用 SVGR,但在嘗試使用 Rollup 時也存在同樣的問題。
uj5u.com熱心網友回復:
問題
通過傳入
typescript: true選項svgr,我期望index.d.tsx根據生成的組件生成一個檔案。
這種預期是不正確的。.tsx如果您指定typescript選項而不是檔案, SVGR 只會生成.d.ts檔案。從檔案(您也找到了):
打字稿
生成
.tsx帶有 TypeScript 型別的檔案。
但是,即使指定了此選項,SVGR 也不會生成.tsx檔案,因為您在 esbuild 插件中使用它。esbuild-plugin-svgr在引擎蓋下使用transform來自@svgr/core(請參閱esbuild-plugin-svgr/index.js:L4)的函式。該transform函式僅將 SVG 轉換為 JSX 或 TSX,但從不寫入輸出。@svgr/cli處理將輸出寫入檔案,例如參見@svgr/cli/src/dirCommand.ts.
解決方案
我認為你有兩個選擇:
從esbuild中分離出SVGR,然后生成一個.d.ts檔案
換句話說,停止使用esbuild-plugin-svgr并@svgr/cli改為使用。然后,您必須在 esbuild 之前運行 SVGR;手動,在腳本中鏈接命令或使用npm 的 pre-script hook。之后,您必須生成一個.d.ts file. 雖然,看看esbuild#95,它似乎并不支持開箱即用。您可能想探索那里列出的建議,包括:
- 使用 TypeScript 編譯器發出宣告檔案 (
tsc --emitDeclarationOnly) - 使用插件,例如
esbuild-plugin-d.ts
您的構建鏈最后可能如下所示:
- 使用 . 從 SVG生成
.tsx檔案@svgr/cli。 - 使用 esbuild 捆綁。
- 生成檔案,可以使用 esbuild 插件
.d.ts作為單獨的步驟,也可以與上述步驟合并。tsc
.d.ts從你的 JavaScript 包生成一個檔案
如果出于某種原因您真的想保留當前的構建配置,您可以使用.d.tsJavaScript 捆綁檔案生成一個檔案tsc dist/index.js --declaration --allowJs --emitDeclarationOnly(請參閱TypeScript 檔案)。需要注意的是,TypeScript 可能無法推斷所有型別,因此您的型別宣告檔案可能不完整。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/481560.html
