在typescript(*.tsx)文件中,我不能用下面的语句导入svg文件:
import logo from './logo.svg';
Transpiler说:[ts]找不到模块'./logo.svg'。 我的svg文件就是<svg>…</svg>。
但在.js文件中,我能够导入它没有任何问题,完全相同的导入语句。我想这与svg文件的类型有关,它必须以某种方式为ts transpiler设置。
你能在ts文件中分享一下如何做到这一点吗?
在typescript(*.tsx)文件中,我不能用下面的语句导入svg文件:
import logo from './logo.svg';
Transpiler说:[ts]找不到模块'./logo.svg'。 我的svg文件就是<svg>…</svg>。
但在.js文件中,我能够导入它没有任何问题,完全相同的导入语句。我想这与svg文件的类型有关,它必须以某种方式为ts transpiler设置。
你能在ts文件中分享一下如何做到这一点吗?
当前回答
你可以像create-react-app一样为svgs声明module:
react-app.d.ts
declare module '*.svg' {
import * as React from 'react';
export const ReactComponent: React.FunctionComponent<React.SVGProps<
SVGSVGElement
> & { title?: string }>;
const src: string;
export default src;
}
看到源
其他回答
感谢smarx指出使用require()。所以在我的例子中,它应该是:
const logo = require("./logo.svg") as string;
在*中工作得很好。tsx文件
如果你使用webpack,你可以通过创建一个自定义类型文件来做到这一点。
创建一个名为custom.d.ts的文件,内容如下:
declare module "*.svg" {
const content: React.FunctionComponent<React.SVGAttributes<SVGElement>>;
export default content;
}
将custom.d.ts添加到tsconfig。Json格式如下
"include": ["src/components", "src/custom.d.ts"]
来源:https://webpack.js.org/guides/typescript/ importing-other-assets
对我来说,我必须包含react-app-env.d。tsconfig*.json:
"include": [
"src/Router.tsx", // my main entry point
"src/global.d.ts", // global stuff
"src/react-app-env.d.ts" // react global stuff
]
如果你正在使用Create-React-App启动器,请确保react-app-env.d。Ts包含如下行:
/// <reference types="react-scripts" />
希望!这会帮助到别人。
实际上,我尝试了所有的步骤,但有一件事我们必须理解,您必须将custom.d.ts文件创建到相应的SVG导入文件夹中。
Ts配置文件
{
"compilerOptions": {
"target": "ES6",
"jsx": "react",
"module": "ESNext",
"moduleResolution": "Node",
"baseUrl": "./",
"paths": {
"@components/*": ["src/components/*"],
"@styles/*": ["src/styles/*"],
"@static/*": ["src/static/*"]
},
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true
},
"include": ["src/**/*", "src/static/optional.d.ts"],
"exclude": ["node_modules", "build"]
}
optional.d.ts
declare module '*.svg' {
import * as React from 'react';
export const ReactComponent: React.FunctionComponent<React.SVGProps<
SVGSVGElement
> & { title?: string }>;
const src: string;
export default src;
}
最后是常用的导出文件:
import Logo from './images/logo.svg';
import BellDot from './images/bell-dot.svg';
import Logout from './images/logout.svg';
import pageNotFound from './images/page-not-found.png';
export {
Logo,
BellDot,
pageNotFound,
Logout
}
更好的主意是: