Skip to content

CodeCoupler Webpack Import SVG Files

There are different ways to import SVG files. Each type of import optimizes the imported SVG files. Metadata, comments, hidden elements, default or suboptimal values, and other unnecessary information will be removed or converted without affecting the rendering result.

Using the <img> Tag

This is the easiest method. Whenever you import an HTML file containing an <img> tag that points to an SVG file, the SVG file will be inlined as the most compact, compressible data URI that browsers supporting SVG tolerate. If the SVG file is too big it will be extracted and saved separately.

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

Import SVG from local directory:

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

Import bootstrap.svg from the node pakage bootstrap-incons:

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

Import SVG Sourcecode and Inject into DOM

You can import the SVG file into your code and retrieve the original <svg> code. Then, you can inject it into the DOM however you need.

The only thing you need to note is that you must append ?source to the file name:

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 by using the command
// 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 a single sprite and separated by different IDs. Then you can use the ID to inject the SVG code into the DOM.

The only thing you need to note is that you must append ?sprite to the file name:

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

// Or import from a package by using the command
// 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 can import all the necessary SVG files into 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";

Then, use the file name (without the 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>