Using with typescript
See original GitHub issue🐛 Bug Report
I’m using @svgr/webpack
inside a TypeScript react project and everything works fine without doing anything fancy! But if i pass props to svg component then i face exceptions. I found many same issues here but all closed without any answer so i’m opening a new one.
Note: I’m inside a monorepo and everything works fine on ReactNative using react-native-svg-transformer with TypeScript.
To Reproduce
<Icon />
This works fine
<Icon width={100} height={100} fill='red' />
This cause exception
Type '{ width: number; height: number; fill: string; }' is not assignable to type 'IntrinsicAttributes'.
Property 'width' does not exist on type 'IntrinsicAttributes'. TS2322
So i tried to pass typescript: true
option in my .svgrrc.js
file to generates .tsx files with TypeScript typings but i get following exception and even using <Icon />
without passing props wont work anymore.
SyntaxError: unknown: Unexpected token, expected "," (3:21)
1 | import * as React from "react";
2 |
> 3 | function SvgEye(props: React.SVGProps<SVGSVGElement>) {
| ^
4 | ...
I tried to use custom template to generate .tsx file but still face same problem.
// .svgrrc.js
module.exports = {
// typescript: true,
ext: 'tsx',
template: function defaultTemplate({ template }, opts, { componentName, jsx }) {
const typeScriptTpl = template.smart({ plugins: ['typescript'] })
return typeScriptTpl.ast`
import * as React from "react"
const ${componentName} = (props: React.SVGProps<SVGSVGElement>) => null;
export default ${componentName}`
},
replaceAttrValues: {
'#707070': '{props.fill}',
},
}
Im returning null
instead of ${jsx}
just to make error message more readable
SyntaxError: unknown: Unexpected token, expected "," (3:21)
1 | import * as React from "react";
2 |
> 3 | const SvgEye = (props: React.SVGProps<SVGSVGElement>) => null;
| ^
4 |
5 | export default SvgEye;
Expected behavior
The typescript: true
option should fix the issue.
Paste the results here:
"devDependencies": {
"@svgr/webpack": "^5.4.0",
"typescript": "^3.9.6"
}
Issue Analytics
- State:
- Created 3 years ago
- Reactions:6
- Comments:11 (1 by maintainers)
Top GitHub Comments
So I had the exact same problem but with nextjs. It seems that when I added
custom.d.ts
with module desciber for*.svg
it seems to work properlyand now type any prop for svg component, the only downside is it doesnt propose any props in IDE, but maybe its my fault, I’m writing in typescript for about a week 😃
Hi, I was just having this problem, and this is how I got it to work: ✅
.svgrrc.js
typescript-template.js
CLI Command:
npx @svgr/cli --out-dir src/assets/svg/SVGComponents --template typescript-template.js --typescript
Hope it serves you well! ☺️