Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.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!

like image 412
Matt Thomas Avatar asked Jan 10 '19 03:01

Matt Thomas


3 Answers

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

like image 50
basarat Avatar answered Oct 27 '22 07:10

basarat


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;
}
like image 28
MarcoLe Avatar answered Oct 27 '22 08:10

MarcoLe


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"]
like image 5
Caio Lucas Avatar answered Oct 27 '22 06:10

Caio Lucas