[英]Importing SVG through a typescript path alias (module not found)
我有一个 create-react-app (CRA),所以我无法访问 webpack.config,我正在使用 typescript 为应用程序的公共核心导入创建路径别名。 这一切正常,我可以通过路径别名导入所有内容,but.svg 文件。
问题:如何通过我的@assets/images/some.svg
路径别名导入.SVG 文件?
.tsconfig
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react",
"baseUrl": "./"
},
"extends": "./paths.json",
"include": [
"src",
"./custom.d.ts"
]
}
路径.json
{
"compilerOptions": {
"paths": {
"@pages": ["src/pages"],
"@pages/*": ["src/pages/*"],
"@hooks": ["src/core/hooks"],
"@hooks/*": ["src/core/hooks/*"],
"@components": ["src/core/components"],
"@components/*": ["src/core/components/*"],
"@containers": ["src/containers"],
"@containers/*": ["src/containers/*"],
"@services": ["src/core/services"],
"@services/*": ["src/core/services/*"],
"@configs": ["src/core/configs"],
"@configs/*": ["src/core/configs/*"],
"@assets": ["src/core/assets"],
"@assets/*": ["src/core/assets/*"],
"@models": ["src/core/models"],
"@models/*": ["src/core/models/*"],
"@store": ["src/core/store"],
"@store/*": ["src/core/store/*"],
"@utils": ["src/core/utils"],
"@utils/*": ["src/core/utils/*"],
"@styles": ["src/core/styles"],
"@styles/*": ["src/core/styles/*"]
}
}
}
自定义.d.ts
declare module '*.svg' {
const content: string;
export default content;
}
在文件中,我正在导入 SVG,如下所示:
import uploadStep1Logo from '@assets/images/UploadConfirmationDialog_Step1.svg';
import uploadStep2Logo from '@assets/images/UploadConfirmationDialog_Step2.svg';
import uploadStep3Logo from '@assets/images/UploadConfirmationDialog_Step3.svg';
出于某种原因,如果我使用绝对路径,它可以工作,但是,如果我使用@assets/...
它无法解决并出现如下错误。
Module not found: Can't resolve '@assets/images/UploadConfirmationDialog_Step1.svg'
看看这个答案: https://stackoverflow.com/a/60598134/11047070 。
但是为了让它工作,你的react-scripts
版本现在必须低于 4.0。
您必须将craco
和craco-alias
包与tsconfig
一起使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.