Strahinja Ajvaz
Strahinja Ajvaz

Reputation: 2643

How to import svg files and use them for src in image

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"
    })
  ]
}

Upvotes: 4

Views: 24117

Answers (2)

Hemadri Dasari
Hemadri Dasari

Reputation: 33994

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

Upvotes: 4

Piotr Szlagura
Piotr Szlagura

Reputation: 672

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.

Upvotes: 0

Related Questions