Using SVGs in Vite

Tutorial 3 of 5

Using SVGs in Vite

1. Introduction

In this tutorial, we'll delve into how to import and utilize SVG files in your Vite projects. SVGs (Scalable Vector Graphics) offer a means to create scalable, high-quality graphics that can be manipulated with CSS and JavaScript.

By the end of this tutorial, you will learn:
- How to import SVGs into your Vite project
- Manipulating SVGs using CSS and JavaScript

Prerequisites:
- Basic knowledge of HTML, CSS, and JavaScript
- Familiarity with Vite

2. Step-by-Step Guide

Importing SVGs

In your Vite project, you can import SVGs just like any other JavaScript module:

import myLogo from './my-logo.svg';

By doing this, you are actually importing the URL of the SVG file. This URL can be used in your HTML in img tags:

<img src={myLogo} alt="My Logo">

Manipulating SVGs with CSS

SVGs are made up of XML-based vector images and are treated as Document Object Model (DOM) elements in the browser. This means they can be styled and manipulated using CSS:

<style>
  svg {
    width: 100px;
    height: 100px;
    fill: red;
  }
</style>

Manipulating SVGs with JavaScript

Similarly, you can manipulate SVGs using JavaScript by accessing the SVGs' DOM API:

const svgElement = document.querySelector('svg');
svgElement.style.fill = 'red';

3. Code Examples

Example 1: Importing SVGs

// Import the SVG file
import myLogo from './my-logo.svg';

// Now `myLogo` is the URL of the SVG file, you can use it in your HTML
console.log(myLogo);  // Expected output: "/assets/my-logo.49a45d.svg"

Example 2: Styling SVGs with CSS

<style>
  /* Change the color and the size of the SVG */
  svg {
    width: 100px;
    height: 100px;
    fill: red;
  }
</style>

Example 3: Manipulating SVGs with JavaScript

// Select the SVG element
const svgElement = document.querySelector('svg');

// Change the color of the SVG
svgElement.style.fill = 'red';

4. Summary

In this tutorial, we've learned how to import SVGs into a Vite project and how to manipulate them using CSS and JavaScript.

Next, you could explore more about SVGs and how to animate them using CSS or JavaScript.

Here are some resources for further learning:
- SVG Tutorial - W3Schools
- SVG Basics—How to Create Simple Shapes and Lines - Tuts+

5. Practice Exercises

  1. Import an SVG image into your Vite project and display it on your webpage.
  2. Use CSS to change the color and size of the SVG image.
  3. Use JavaScript to change the color of the SVG image when a button is clicked.

Solutions:

  1. Check the code examples above for reference.
  2. Use the fill property in CSS to change the color, and width and height properties to change the size.
  3. Attach an event listener to the button and change the fill property of the SVG using JavaScript when the button is clicked.

Remember, practice makes perfect! Keep experimenting with different SVGs and manipulating them using CSS and JavaScript.