I'm trying to import an .svg
file as a React component with TypeScript.
According to the React docs, this is done like so:
import { ReactComponent as Icon } from './Icon.svg';
Following the TypeScript docs, I've added this:
// custom.ts.d
declare module '*.svg' {
const content: any;
export default content;
}
and
// tsconfig.json
{
...
"files": [
"custom.d.ts"
]
}
The SVG is rendering. But I'm getting a TypeScript error:
[ts] Module '"*.svg"' has no exported member 'ReactComponent'. [2305]
Here is my full tsconfig
file if that helps:
{
"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"
]
}
Thank you!
You have export default content;
But you are doing a named import (not a default import).
Change declaration to export the name you are importing:
declare module '*.svg' {
import React = require('react');
export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
const src: string;
export default src;
}
Recommend not using files
in tsconfig.json. Instead just use include
2019 In addition to @basarat's answer: React.SFC
is depracated now consider using React.FunctionComponent
like:
declare module '*.svg' {
import React = require('react');
export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
const src: string;
export default src;
}
You're naming the custom types as custom.ts.d
and it should call custom.d.ts
once the ts compiler is configured to process ts|tsx
extensions.
After that, you should be able to reference it into your tsconfig.json
include section just like this:
"include": ["custom.d.ts"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With