16

I have an angular2 project which was created via angular-cli. In webpack there is a loader to load the svg sprite and also to generate that sprite from list of svgs. But how do I can use this functionality in my current project when angular-cli doesn't allow me to change webpack.config?

Thanks.

Igor JS
  • 208
  • 2
  • 7

1 Answers1

40

Use svg-sprite

1. npm install --save-dev svg-sprite

2. Put your svgs in src/svgs

3. Add sprite-config.json to your project root

{
    "dest": "src/",
    "mode": {
        "css": {
            "dest": "sprites",
            "render": {
                "scss": {
                    "dest": "_sprite.scss"
                }
            }
        }
    }
}

4. Add a script to package.json

"sprites": "svg-sprite --config sprite-config.json src/svgs/*.svg"

5. Add @import to your main styles.scss

@import './sprites/sprite';

6. Run script using npm run sprites

Optional: create a build script

Add this to your scripts to build in one step

"start": "npm run sprites && ng serve",
"build": "npm run sprites && ng build --prod"
adriancarriger
  • 2,970
  • 3
  • 19
  • 26
  • This is just awesome! Thank you very much. – Igor JS Dec 27 '16 at 09:24
  • Great! If you've found this helpful please consider up voting/accepting the answer. Thank you! – adriancarriger Dec 27 '16 at 17:16
  • Well at the moment I can't vote/accept the answer. My reputation is a bit low for that now. I'm new here. – Igor JS Jan 04 '17 at 04:07
  • 2
    This generates a stylesheet with classes, referencing the svg's as a background. I would prefer no css to be generated, and just use this syntax: I prefer this approach because i find it easier to scale the svgs like this. – Davy Dec 31 '17 at 14:18
  • @Davy So have you found a way to use no-css approach with angular cli? – Dmitry Feb 03 '18 at 23:44
  • Well, yes, but not in a very elegant way – Davy Feb 05 '18 at 06:31
  • 1
    @Davy instead of 'css' mode that was provided in the example use 'symbol' mode. – Igor JS Feb 24 '18 at 20:30
  • I am also looking for a non-CSS way to use SVG sprites in my Angular app. I have posted a question that targets this specific issue: https://stackoverflow.com/questions/50459291 – Zythyr May 22 '18 at 06:10
  • nice solution, but do you know of a way that this build would be integrated to `ng serve` so that a change in `svg` files would result in browser reload? – azerafati Apr 25 '19 at 07:39