4

I'm running into an issue that I can't seem to solve.

I have a svg file that I need to include in my project. Since I've build my own boilerplate I want to have the same functionality as CRA in that I can use the svg as the image src.

i.e.

<img src={svgfile} alt="some file" />

What would I need to do to have that functionality?
I tried to use file loader to get it to work but it throws an error.

{
    test: /\.(png|jpg|gif|svg)$/,
    use: [
      {
        loader: "file-loader",
        options: {}
      }
    ]
  },

Any help would be greatly appreciated.

SA

webpack file

{
  entry: "./src/browser/index.js",
  output: {
    path: path.resolve(__dirname, "public"),
    filename: "bundle.js",
    publicPath: "/"
  },
  module: {
    rules: [
      { test: /\.(js)$/, use: "babel-loader" },
      {
        test: /\.(png|jpg|gif|svg)$/,
        use: [
          {
            loader: "file-loader",
            options: {}
          }
        ]
      },
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      __isBrowser__: "true"
    })
  ]
}
Towkir
  • 3,889
  • 2
  • 22
  • 41
Strahinja Ajvaz
  • 2,521
  • 5
  • 23
  • 38

2 Answers2

3

Like

 import svgfile from “./path/fileName.svg”;

 <img src={svgfile} alt="some file" />

Or

<img src={require(“./path/fileName.svg”} alt="some file" />

Please excuse me for double quotes I am answering in mobile

vsync
  • 118,978
  • 58
  • 307
  • 400
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
0

You can try something like:

test: /\.(?:png|jpg|gif|svg)$/i,
use: [
  {
    loader: 'file-loader',
    options: {
      name: 'assets/[hash].[ext]',
    }
  },
]

Where assets is directory where imported file will be stored after build.

Piotr Szlagura
  • 650
  • 5
  • 15