Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import SVG in TypeScript React app with Webpack

I'd like to import an SVG image into a little React app written with TypeScript and bundled with Webpack. The problem is that that no image is shown (only the browser's fallback image that no image was found). It seems like the data URL is wrong, because when I copy the data URL in a base64 decoder the image is broken.

I'm tried different Webpack loaders (url-loader, file-loader, svg-loader, ...)

webpack.config.json

module: {
  rules: [
    {
      test: /\.svg$/,
      loader: 'url-loader'
    }
  ]
}

tsd.d.ts

declare module "*.svg" {
  const content:string;
  export default content;
}

App.tsx

import content from './logo.svg';

class App extends React.Component {
  render() {
    <div>
      <img src={content} />
    </div>
  }
}

Any ideas what to change?

Thanks in advance!

like image 875
lehnerchristian Avatar asked Jan 29 '23 10:01

lehnerchristian


1 Answers

My problem was that Webpack was misconfigured.

I had, beside others, the following two loader configurations:

module: {
  rules: [
    {
      test: /\.svg$/,
      loader: 'url-loader'
    },
    {
      test   : /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
      loader : 'file-loader'
    }
  ]
}

The problem was that I had svg in both rules, therefore webpack used the wrong loader. Removing the svg part from the second rule solved the issue

like image 122
lehnerchristian Avatar answered Feb 03 '23 07:02

lehnerchristian