Search code examples
javascriptreactjssvgwebpackwebpack-2

Webpack2 - How to inline an SVG file


In webpack.config.js I am using the following loader:

{
  test: /\.svg$/,
  use: [ 'file-loader' ]
}

Then in my component:

import icon from '../img/icons/menu.svg'

However, console.log(icon) // 58f714c05099311f302aeb7d346be056.svg shows that the value of icon is just a filename.

Is there a way to import the raw svg?

Update:

Using url-loader imports the svg as a base64 string.

<img src="data:image/svg+xml;base64,PHN2ZyBjbGFzcz0ibWVudS1pY29uIiB3aWR0aD0iMzBweCIgaGVpZ2h0PSIzMHB4IiB2aWV3Qm94PSIwIDAgMzAgMzAiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik00LDEwaDI0YzEuMTA0LDAsMi0wLjg5NiwyLTJzLTAuODk2LTItMi0ySDRDMi44OTYsNiwyLDYuODk2LDIsOFMyLjg5NiwxMCw0LDEweiBNMjgsMTRINGMtMS4xMDQsMC0yLDAuODk2LTIsMiAgczAuODk2LDIsMiwyaDI0YzEuMTA0LDAsMi0wLjg5NiwyLTJTMjkuMTA0LDE0LDI4LDE0eiBNMjgsMjJINGMtMS4xMDQsMC0yLDAuODk2LTIsMnMwLjg5NiwyLDIsMmgyNGMxLjEwNCwwLDItMC44OTYsMi0yIFMyOS4xMDQsMjIsMjgsMjJ6Ii8+PC9zdmc+Cg==">

However, this also is not ideal since I am not able to style the svg with CSS.


Solution

  • module.loaders =  ...
      {
          test: /\.(svg)$/,
          loader: 'raw-loader'
      }
    

    This is because you are having the inline svg. Ref