简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM