Skip to content

🎨 Simplify SVG icon usage in your Angular project! Enhance the flexibility and manageability of your Angular project by using SVG sprites.

License

Notifications You must be signed in to change notification settings

bodnya29179/Angular-Svg-Sprite

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Angular SVG Sprite

The aim

The project aims to generate an SVG sprite that enables us to achieve the following objectives:

  • Optimize the use of SVG files through the creation of an SVG icon component;
  • Allow the editing of SVG files without losing their functionality when using the <img/> tag.
  • Automatically regenerate the SVG sprite when icons are added, edited, or removed, and the app is running.
  • Reduce the number of HTTP requests when fetching icons from the assets folder by using a service for loading SVG icons.

Installation

Run the commands:

  • npm install svg-sprite --save-dev
  • npm install onchange --save-dev

Steps

1. Creating the svg-sprite generation script:

Where:

  • ICONS_PATH is the path where your svg-icons are located;
  • SVG_SPRITE_PATH is the path where your generated sprite will be located;
  • SVG_SPRITE_FILENAME is the name of the sprite that you want to save.

2. Creating the services that work with sprite:

3. Creating the svg-icon component:

4. Adding the commands to package.json:

  • start allows us to generate the svg-sprite when we run our app & run the app:

    "start": "npm run generate-sprite && ng serve && npm run watch-sprite"
  • build allows us to prepare the svg-sprite before making the app build & build the app:

    "build": "npm run generate-sprite && ng build"
  • generate-sprite allows us to generate the svg-sprite file by running the script:

    "generate-sprite": "node scripts/generate-svg-sprite.js"
  • watch-sprite allows us to listen the svg-icon changes during the running of app (adding/editing/removing icons, etc.) & regenerate the sprite build:

    "watch-sprite": "onchange \"./src/assets/icons/**/*.svg\" --initial --kill -- npm run generate-sprite"

5. Adding svg-icons to the assets folder.

6. Adding the svg-sprite to the .gitignore file for not saving it:

# Auto-generated sprites folder
svg-sprite.svg

7. Using the svg-icon component:

Adding icons to template:

<svg-icon [src]="<your-icon-name-here>"></svg-icon>

Changing icon styles (optional):

svg-icon::ng-deep {
  svg path {
    fill: <some-color-here>;
  }
}

or

svg-icon::ng-deep {
  svg path {
    stroke: <some-color-here>;
  }
}

The usage of fill or stroke depends on the <path> type in the svg file.

About

🎨 Simplify SVG icon usage in your Angular project! Enhance the flexibility and manageability of your Angular project by using SVG sprites.

Topics

Resources

License

Stars

Watchers

Forks