reactjstypescriptsvg

TypeScript - Module '"*.svg"' has no exported member 'ReactComponent


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.d.ts

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!


Solution

  • You have export default content; But you are doing a named import (not a default import).

    Fix

    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;
    }
    

    Additional

    Recommend not using files in tsconfig.json. Instead just use include