question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

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:closed
  • Created 3 years ago
  • Reactions:6
  • Comments:11 (1 by maintainers)

github_iconTop GitHub Comments

9reactions
michalpokojskicommented, Jul 22, 2020

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 properly

// custom.d.ts

declare module '*.svg' {
  import * as React from 'react';

  const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;

  export default ReactComponent;
}
// next.config.js (where I inject webpack support to next webpack config)

module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/,
      use: [
        {
          loader: '@svgr/webpack',
        },
      ],
    });

    return config;
  },
};

and 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 😃

5reactions
bernardoamimcommented, Dec 5, 2020

Hi, I was just having this problem, and this is how I got it to work: ✅

.svgrrc.js

module.exports = {
  template: require('./typescript-template'),
  ext: 'tsx',
  prettierConfig: {
    parser: 'typescript',
  },
  jsx: {
    babelConfig: {
      plugins: [
        // I removed these properties to have full control over them
        [
          '@svgr/babel-plugin-remove-jsx-attribute',
          {
            elements: ['path'],
            attributes: ['strokeWidth', 'stroke'],
          },
        ],
      ],
    },
  },
}

typescript-template.js

function typescriptTemplate(
  { template },
  opts,
  { imports, interfaces, componentName, props, jsx, exports },
) {
  const plugins = ['jsx'];

  if (opts.typescript) {
    plugins.push('typescript')
  }

  const typeScriptTpl = template.smart({ plugins });

  const formattedName = `${componentName.name}: React.FC<React.SVGProps<SVGSVGElement>>`

  return typeScriptTpl.ast`
  import React from 'react';

  const ${formattedName} = ${props} => {
    return ${jsx};
  }

  ${exports}
  `
}

module.exports = typescriptTemplate
`

CLI Command:

npx @svgr/cli --out-dir src/assets/svg/SVGComponents --template typescript-template.js --typescript

Hope it serves you well! ☺️

Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeScript: JavaScript With Syntax For Types.
TypeScript understands JavaScript and uses type inference to give you great tooling without additional code. Get Started. Handbook. Learn the language.
Read more >
Get Started With Typescript in 2019 - Robert Cooper
1. Install the TypeScript compiler. To start off, the TypeScript compiler will need to be installed in order to convert TypeScript files into ......
Read more >
How to Use TypeScript – Beginner-Friendly TS Tutorial
TypeScript is a superset of JavaScript. Superset means that it adds features on top of what JavaScript offers. TypeScript takes all the ...
Read more >
What is TypeScript and why should you use it? - Contentful
TypeScript extends JavaScript and improves the developer experience. It enables developers to add type safety to their projects. Moreover, ...
Read more >
Create an ASP.NET Core app with TypeScript - Visual Studio
Add the NuGet package for TypeScript support; Add some TypeScript code; Run the app; Add a third-party library using npm. Prerequisites. You ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found