Skip to content

CodeCoupler Webpack Import SVG Files

You can import SVG files in different ways. For each type of import, the imported SVG files are optimized. Metadata, comments, hidden elements, default or suboptimal values and other stuff will be removed or converted without affecting the rendering result.

Using the <img> Tag

This is the easiest method. Whnever you import HTML files containing an <img> tag pointing to an SVG file, the SVG file will be inlined as most compact, compressible data URI that SVG-supporting browsers tolerate. Should be the SVG file to big it will be extracted and saved separetely.

The only thing you need to pay attention to is the referring to SVG files from node packages. Here you have to start the path with ~:

Import SVG from local directory:

<img src="./local/file.svg" />

Import bootstrap.svg from node pakage bootstrap-incons:

<img src="~bootstrap-icons/icons/bootstrap.svg" />

Import SVG Sourcecode and Inject into DOM

You can import the SVG file somewhere in your code and retrieve the origin <svg> code. You can inject this into the DOM however you need.

The only thing you need to pay attention to is that you have to append ?source to the filename:

1
2
3
4
5
6
7
// This will import the SVG code into the variable mySvg:
import mySvg from "./some/file.svg?source";

// Or import from a package with
// import mySvg from "bootstrap-icons/icons/bootstrap.svg?source";

document.getElementById("some-id").insertAdjacentHTML('beforeend', mySvg);

Import into a Sprite

You can import SVG files which will be collected into one single sprite separated by different id's. Then you can use the id to inject SVG code into the DOM.

The only thing you need to pay attention to is that you have to append ?sprite to the filename:

// This will import the SVG code into the global sprite:
import mySvg from "./local/file.svg?sprite";

// Or import from a package with
// import mySvg from "bootstrap-icons/icons/bootstrap.svg?sprite";

// The variable mySvg contains all needed
// variables to create a <svg> tag:
document.getElementById("some-id").insertAdjacentHTML(
  "beforeend",
  `<svg viewBox="${codeSpriteLocal.viewBox}" height="32px">
  <use xlink:href="#${codeSpriteLocal.id}" />
  </svg>`
);

You could even import all needed SVG files somewhere in your bundle without using a variable name:

1
2
3
import "./local/alert.svg?sprite";
import "./local/cancel.svg?sprite";
import "./local/start.svg?sprite";

And use the filename (without extension) appended with --sprite as id to insert <svg> tags in your HTML files:

1
2
3
<svg height="32px"><use xlink:href="#alert--sprite" /></svg>
<svg height="32px"><use xlink:href="#cancel--sprite" /></svg>
<svg height="32px"><use xlink:href="#start--sprite" /></svg>