我有一个 create-react-app (CRA),所以我无法访问 webpack.config,我正在使用 typescript 为应用程序创建通用核心导入的路径别名。这一切正常,我可以通过路径别名导入所有内容,但 .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"
]
}
path.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/*"]
}
}
}
custom.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'
答案 0 :(得分:0)
看看这个答案:https://stackoverflow.com/a/60598134/11047070。
但为了使其正常工作,您的 react-scripts
版本目前必须低于 4.0。
答案 1 :(得分:0)
您必须将 craco
和 craco-alias
包与 tsconfig
一起使用