Mat*_*mas 3 svg typescript reactjs
我正在尝试.svg使用TypeScript 将文件作为React组件导入。
根据React文档,这样做是这样的:
import { ReactComponent as Icon } from './Icon.svg';
在TypeScript文档之后,我添加了以下内容:
// custom.ts.d
declare module '*.svg' {
const content: any;
export default content;
}
Run Code Online (Sandbox Code Playgroud)
和
// tsconfig.json
{
...
"files": [
"custom.d.ts"
]
}
Run Code Online (Sandbox Code Playgroud)
SVG正在渲染。但是我收到一个TypeScript错误:
[ts] Module '"*.svg"' has no exported member 'ReactComponent'. [2305]
这是我的完整tsconfig文件,如果有帮助的话:
{
"compileOnSave": false,
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"outDir": "./dist",
"strict": true,
"jsx": "react",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"removeComments": false,
"preserveConstEnums": true,
"sourceMap": true,
"skipLibCheck": true,
"esModuleInterop": true,
"baseUrl": ".",
"plugins": [
{
"name": "typescript-styled-plugin"
}
],
"typeRoots": ["./node_modules/@types"],
"lib": ["dom", "es2015", "es2017"]
},
"exclude": ["node_modules", "dist"],
"files": [
"custom.d.ts"
]
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Mar*_*oLe 11
2019除了@basarat 的回答:React.SFC现在已弃用,请考虑使用React.FunctionComponent:
declare module '*.svg' {
import React = require('react');
export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
const src: string;
export default src;
}
Run Code Online (Sandbox Code Playgroud)
小智 10
如果您已经vite-plugin-svgr安装了插件,只需将以下行添加到您的vite-env.d.ts文件中:
/// <reference types="vite-plugin-svgr/client" />
Run Code Online (Sandbox Code Playgroud)
小智 9
您将自定义类型命名为,一旦 ts 编译器配置为处理扩展custom.ts.d,它就应该调用。custom.d.tsts|tsx
之后,您应该能够将其引用到您的tsconfig.json包含部分中,如下所示:
"include": ["custom.d.ts"]
Run Code Online (Sandbox Code Playgroud)
您有export default content;但是您正在执行命名导入(不是默认导入)。
更改声明以导出您要导入的名称:
declare module '*.svg' {
import React = require('react');
export const ReactComponent: React.SFC<React.SVGProps<SVGSVGElement>>;
const src: string;
export default src;
}
Run Code Online (Sandbox Code Playgroud)
建议不要files在tsconfig.json中使用。而是只使用include
小伙伴们,如果您使用的是Vite和vite-plugin-svgr,请按照以下步骤操作:
创建一个声明文件,名称:client.d.ts (在types文件夹或根目录中无关紧要)
将这行代码添加到该文件中:
/// <reference types="vite-plugin-svgr/client" />
Run Code Online (Sandbox Code Playgroud)
重新启动应用程序
或者
将这行代码添加到您的tsconfig.js中:
types": ["vite-plugin-svgr/client"]
Run Code Online (Sandbox Code Playgroud)
重新启动应用程序
就我个人而言,我想使用第一种解决方案。
更新 - - - - - - - - - - - - - - - - - - - - - - - -
在新版本(4.x)中,您应该像这样使用SVG:
import Logo from "./logo.svg?react";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1453 次 |
| 最近记录: |