Error in plugin gulp svg sprite

Error in plugin ‘gulp-svg-sprite’ #5 Comments When adding a new svg to an existing project I am getting the following error: The svg is a direct copy of an existing svg from the project which was previously successfully ‘sprited’ (Eliminating possibility of corrupt svg). Something else has changed causing this error. Any clues? I’m […]

Содержание

  1. Error in plugin ‘gulp-svg-sprite’ #5
  2. Comments
  3. gulp-svg-sprite
  4. Features & configuration? в†’ svg-sprite
  5. Usage
  6. svgSprite(options)
  7. options.dest
  8. Examples
  9. Basic example
  10. Gulp 4 basic example
  11. More complex example
  12. Error handling
  13. Advanced features
  14. Changelog
  15. Создание SVG sprite с помощью gulp
  16. svg-sprite/gulp-svg-sprite
  17. Sign In Required
  18. Launching GitHub Desktop
  19. Launching GitHub Desktop
  20. Launching Xcode
  21. Launching Visual Studio Code
  22. Latest commit
  23. Git stats
  24. Files
  25. README.md
  26. About
  27. Example in readme not working. #1
  28. Comments

Error in plugin ‘gulp-svg-sprite’ #5

When adding a new svg to an existing project I am getting the following error:

The svg is a direct copy of an existing svg from the project which was previously successfully ‘sprited’ (Eliminating possibility of corrupt svg). Something else has changed causing this error. Any clues?

I’m using a MAC / Node / NPM

The text was updated successfully, but these errors were encountered:

Hmm, interesting. Are you able to isolate and upload a zip of the files?

Sure you can download the zip located here:
https://www.drupal.org/project/sector
And navigate to the theme folder:
http://cgit.drupalcode.org/sector/tree/themes/contrib/sector_starter
This repo does not contain the test icon—download-purple.svg but is the same code base where I received the error. Thanks.

Thanks Mike, Yes permissions are an area I’ve looked at. It seems that the target ../../scss/generic/_sprite.scss is not being re/written.

I’ve had a quick look this morning and there are a few different issues here (I didn’t manage to get the skipping % but I have seen it before.

To make the sprite override:

  1. Make sure all your paths in the file are up to date. I have to change a few to get the expected result. All the paths are relative to the gulpfile (you have a few ../../ which will make it two folders above the gulpfile
  2. The main reason your sprite wasn’t being overwritten was that the sprite task doesn’t have a destination pipe — this is crucial. Despite the plugin itself having paths the main sprite image needs to know where to go.

Let me know how you get on.

Ah ha thanks Mike. look what I found in a recent commit. Thanks for the code review! I’ll be chatting to my colleague later! http://cgit.drupalcode.org/sector/commit/?id=9619cad19fb2c4c369be62cba06a03a2c574b2ec

Haha! Let me know how you get on

How did you get on @racinggrinner?

Hi Mike, Sorry for the delay, I’ve been away on leave for a few weeks. The chat went well. He has his tail between his legs now! Never remove something you don’t understand! Thanks again.

Источник

gulp-svg-sprite

is a Gulp plugin wrapping around svg-sprite which takes a bunch of SVG files, optimizes them and bakes them into SVG sprites of several types:

  • Traditional CSS sprites for use as background images,
  • CSS sprites with pre-defined elements, useful for foreground images as well,
  • inline sprites using the element,
  • inline sprites using the element
  • and SVG stacks.

Features & configuration? в†’ svg-sprite

This document covers only gulp specific installation and configuration aspects. For a full list of features and options, please see the svg-sprite manual.

Usage

First, install gulp-svg-sprite as a development dependency:

Then, add it to your gulpfile.js :

NOTICE: By default, svg-sprite doesn’t send any files downstream unless you configure it. There are tons of options available — please see below for some basic examples. Also, you should possibly take care of errors that might occur.

svgSprite(options)

As options argument you may provide a main configuration object as described in the svg-sprite manual. Configuration-wise, svg-sprite and gulp-svg-sprite differ only in one respect:

options.dest

Type: String Default value: ‘.’

With Gulp, there is no need to specifiy a main output directory, as the generated files are piped to the next step of the running task anyway. The options.dest value (if given) is simply ignored.

Examples

Basic example

In this very basic example, mostly default settings will be applied to create a traditional CSS sprite (bundle of SVG sprite and CSS stylesheet).

The following files and directories are created:

The cryptical looking part in the SVG’s file name is the result of svg-sprite‘s cache busting feature which is enabled by default for CSS sprites. We’ll turn this off in the next example.

Gulp 4 basic example

More complex example

The following example is a little more complex:

  • We’ll create a В«viewВ» CSS sprite and a В«symbolВ» sprite in one go.
  • Instead of CSS, we’ll render a Sass stylesheet resource for the В«viewВ» sprite.
  • We’ll turn off cache busting for the В«viewВ» sprite and create extra CSS rules specifying each shape’s dimensions.
  • We’ll downscale the SVG shapes to 32Г—32 pixels if necessary and add 10 pixels padding to all sides.
  • We’ll keep the intermediate SVG source files.

The following files and directories are created:

Error handling

Errors might always happen — maybe there are some corrupted source SVG files, the default SVGO plugin configuration is too aggressive or there’s just an error in svg-sprite‘s code. To make your tasks more robust, you might consider using plumber and adding your custom error handling:

Advanced features

For more advanced features like

Changelog

Please refer to the GitHub releases for a complete release history.

Источник

Создание SVG sprite с помощью gulp

Для начала необходимо, что-бы был установлен gulp (если он не установлен, то устанавливаем с помощью npm install gulp)

Далее устанавливаем модуль npm install —save-dev gulp-svg-sprite

Далее в файле gulpfile.js создаем task в котором делаем необходимые настройки модуля, про которые можно прочесть перейдя по ссылке www.npmjs.com/package/svg-sprite

модуль имеет множество настроек и несколько разных модов

В данном случае нас интересует создание спрайта, который можно использовать как в HTML, так и с помощью фоновой картинки в CSS

для этого нам потребуется mode: stack

добавляем код в файл gulpfile.js

Чтобы запустить созданную задачу необходимо в консоле прописать gulp svgSprite

если задача успешно отработала, то увидим сообщение в консоле Finished ‘svgSprite’ after 884 ms

И теперь можно проверять наличие созданного файла с названием, которое мы задали в настройках, в данном случае sprite.svg

он должен находиться по указанному нами пути app/design/frontend/Magento/vendor/web/images/

В спрайт добавляются все иконки находящиеся в каталоге, который мы указали в настройках, в данном случае app/design/frontend/Magento/vendor/web/sprite/*.svg

и каждой иконке присваивается id который соответствует имени файла (id так же можно менять в настройках, это описано в документации)

Чтобы обратиться к нужной иконке из спрайта необходимо к имени файла sprite.svg дописать id иконки, например sprite.svg#shopping-cart

Теперь можно использовать наш спрайт, это можно делать как с помощью HTML так и с помощью CSS, используя background

мы можем менять ширину и высоту иконок с помощью селекторов CSS width и height

если мы добавим спрайт в HTML с помощью svg, то можем менять и цвет иконок с помощью селектора CSS fill

Источник

svg-sprite/gulp-svg-sprite

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

is a Gulp plugin wrapping around svg-sprite which takes a bunch of SVG files, optimizes them and bakes them into SVG sprites of several types:

  • Traditional CSS sprites for use as background images,
  • CSS sprites with pre-defined elements, useful for foreground images as well,
  • inline sprites using the element,
  • inline sprites using the element
  • and SVG stacks.

This document covers only gulp specific installation and configuration aspects. For a full list of features and options, please see the svg-sprite manual.

First, install gulp-svg-sprite as a development dependency:

Then, add it to your gulpfile.js :

NOTICE: By default, svg-sprite doesn’t send any files downstream unless you configure it. There are tons of options available — please see below for some basic examples. Also, you should possibly take care of errors that might occur.

As options argument you may provide a main configuration object as described in the svg-sprite manual. Configuration-wise, svg-sprite and gulp-svg-sprite differ only in one respect:

Type: String Default value: ‘.’

With Gulp, there is no need to specifiy a main output directory, as the generated files are piped to the next step of the running task anyway. The options.dest value (if given) is simply ignored.

In this very basic example, mostly default settings will be applied to create a traditional CSS sprite (bundle of SVG sprite and CSS stylesheet).

The following files and directories are created:

The cryptical looking part in the SVG’s file name is the result of svg-sprite‘s cache busting feature which is enabled by default for CSS sprites. We’ll turn this off in the next example.

Gulp 4 basic example

More complex example

The following example is a little more complex:

  • We’ll create a «view» CSS sprite and a «symbol» sprite in one go.
  • Instead of CSS, we’ll render a Sass stylesheet resource for the «view» sprite.
  • We’ll turn off cache busting for the «view» sprite and create extra CSS rules specifying each shape’s dimensions.
  • We’ll downscale the SVG shapes to 32×32 pixels if necessary and add 10 pixels padding to all sides.
  • We’ll keep the intermediate SVG source files.

The following files and directories are created:

Errors might always happen — maybe there are some corrupted source SVG files, the default SVGO plugin configuration is too aggressive or there’s just an error in svg-sprite‘s code. To make your tasks more robust, you might consider using plumber and adding your custom error handling:

For more advanced features like

Please refer to the GitHub releases for a complete release history.

Copyright © 2018 Joschi Kuphal joschi@kuphal.net / @jkphl. svg-sprite is licensed under the terms of the MIT license. The contained example SVG icons are part of the Tango Icon Library and belong to the Public Domain.

About

SVG sprites & stacks galore — Gulp plugin wrapping around svg-sprite that reads in a bunch of SVG files, optimizes them and creates SVG sprites and CSS resources in various flavours

Источник

Example in readme not working. #1

Your example in the readme:

does not actually send any files down stream I had a quick skim through the re-written svg-sprite module and I think you’ll need to specify a default config that can be extended in this gulp plugin.

then everything works as expected 🙂

The text was updated successfully, but these errors were encountered:

yes, you’re right — the first example was just intended to show the general usage, not a particular configuration (that’s what the basic example is about), but maybe that’s misleading. I’ll add at least something like /* put your configuration here . */ to clarify.

Thanks for reviewing it anyway! 🙂

I modified the README — should be clear now, right?

Ahh yes, much clearer 🙂

Is there anything baked into your plugin that svg-sprite is missing? Anything I should cross-port? (Except the PNG fallback part — that’s iconizr’s job, and I will start rewriting that in the next couple of days as well . )

Wanted to comment here on a feature of @shakyShane’s plugin that I’m missing with this one: the ability to customize svg symbol ids.

Essentially, instead of name of I’d like it to have . And of course this icon- prefix should be added to each svg symbol.

The prefix option seemed like the way to do this, but in my current implementation it’s only applying the prefix to the wrapper.

It’s possible that I’m doing something wrong. Here’s what I’ve tried:

Let me know if I’m simply missing something. Otherwise, I’d love to see this feature ported over from @shakyShane’s plugin.

Источник

Действительно была виновата иконка, а не gulp-svg-sprite.
На мой взгляд — это плохая практика рисовать векторное изображение в растровом редакторе, а затем плагином фотошопа переводить из растра в вектор.
Поэтому и получился очень странный код с запутанными стилями, с присвоением классов каждой строчке и уникальными идентификаторами на русском языке.
К счастью они не использовались, поэтому иконка отображалась.
Почистил этот весь мусор, оптимизировал код вручную, так как автоматические оптимизаторы тут не сработали бы, из-за «оригинальности» кода.

Вывод:

Для векторных изображений используйте только векторные редакторы, например Incscape, Adobe Illustrator и другие SVG редакторы.

Ниже код, что получилось в итоге, сравните с исходным кодом

<svg version="1.1"
     baseProfile="full"
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     viewBox="0 0 62 38.5" >

    <defs>
        <style>
            .acls-1
			{fill:none;
			stroke:#656565;
			}
   		</style>
    </defs>
       <g class="acls-1" >
        <path  d="M.5 14h18v8H.5M.5 21h18v8H.5M43.5 21h18v8h-18M.5 14h18v21H.5z" />
        <path  d="M43.5 14h18v21h-18z"/>
		</g>
      <g  class="acls-1" transform="translate(-663.5 -55)">    
		<path   d="M682 77v-1h26v1h-26z"   />
        <path   d="M682 70a23.828 23.828 0 0 1 12-3 30.611 30.611 0 0 1 13 3" />
        <path   d="M682 83s4.362 2 12 2a40.779 40.779 0 0 0 13-2"  />
        <path   d="M682 89s2.289 3 9 3"  />
        <path   d="M690 59h1v34h-1V59z"  />
        <path   d="M697 59h1v34h-1V59z"   />
        <path   d="M703 60h1v32h-1V60z"    />
        <path   d="M685 60h1v32h-1V60z"  />
        <path   d="M682 70h-1v-7h1v7z"    />
        <path   d="M708 70h-1v-7h1v7z"  />
        <path   d="M681 63s1.75-4 13-4 14 4 14 4" />
        <path   d="M670 70h1v13h-1V70z"  />
        <path   d="M676 70h1v13h-1V70z"  />
        <path   d="M712 70h1v13h-1V70z"  />
        <path   d="M718 70h1v13h-1V70z"  />
        <path   d="M681 63h-1v-4h1v4z"   />
        <path   d="M709 63h-1v-4h1v4z"    />
        <path   d="M680 60s1.958-4.484 14-4.484S709 60 709 60"  />
        <path   d="M707 90s-1.215 3-10 3" />
        </g>    
		</svg> 

Попробуйте убрать: fill:none; и получите картинку, которую привели в вопросе.
Вот это и случилось после обработки gulp-svg-sprite

 $('[fill]').removeAttr('fill');
            $('[stroke]').removeAttr('stroke');
            $('[style]').removeAttr('style');      
<svg version="1.1"
     baseProfile="full"
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     viewBox="0 0 62 38.5" >

    <defs>
        <style>
            .acls-1
			{
			stroke:#656565;
			}
   		</style>
    </defs>
      
      <g  class="acls-1" transform="translate(-663.5 -55)">    
		<path   d="M682 77v-1h26v1h-26z"   />
        <path   d="M682 70a23.828 23.828 0 0 1 12-3 30.611 30.611 0 0 1 13 3" />
        <path   d="M682 83s4.362 2 12 2a40.779 40.779 0 0 0 13-2"  />
        <path   d="M682 89s2.289 3 9 3"  />
        <path   d="M690 59h1v34h-1V59z"  />
        <path   d="M697 59h1v34h-1V59z"   />
        <path   d="M703 60h1v32h-1V60z"    />
        <path   d="M685 60h1v32h-1V60z"  />
        <path   d="M682 70h-1v-7h1v7z"    />
        <path   d="M708 70h-1v-7h1v7z"  />
        <path   d="M681 63s1.75-4 13-4 14 4 14 4" />
        <path   d="M670 70h1v13h-1V70z"  />
        <path   d="M676 70h1v13h-1V70z"  />
        <path   d="M712 70h1v13h-1V70z"  />
        <path   d="M718 70h1v13h-1V70z"  />
        <path   d="M681 63h-1v-4h1v4z"   />
        <path   d="M709 63h-1v-4h1v4z"    />
        <path   d="M680 60s1.958-4.484 14-4.484S709 60 709 60"  />
        <path   d="M707 90s-1.215 3-10 3" />
        </g>    
		
		 <g class="acls-1" >
        <path  d="M.5 14h18v8H.5M.5 21h18v8H.5M43.5 21h18v8h-18M.5 14h18v21H.5z" />
        <path  d="M43.5 14h18v21h-18z"/>
		</g>
		</svg>

Еще один довод за — выбирать иконки с простым, читаемым кодом, чтобы после варки спрайта можно было-бы разобраться и внести незначительные корректировки.

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

ylokesh

Since last day, while doing the build we are getting following error:

Optimizing "%s" with SVGO failed with error "%s"

While problem analysis, found that one of the sub-sub-dependency i.e. SVGO has made a release last day which is causing this issue.

Can you please help us resolving this issue? or suggest an interim resolution.

Package.json
«gulp-svg-sprite»: «^1.4.0»

Thanks in advance.

Screenshot 2019-10-30 at 5 02 12 PM

jonnitto

Since version 1.4 I got always the following error:

Optimizing "%s" with SVGO failed with error "%s"

OS: macOS 10.13.6
node: v10.10.0
npm: 6.4.1

Baldrani

capture d ecran 2018-06-21 a 14 43 08

This is my conf :

const configSvgSprite = {
    shape: {
        spacing: { // Add padding
            padding: 10
        }
    },
    mode: {
        css: { // Activate the «css» mode
            prefix: '.icon-',
            sprite: '../' + joli.build + '/assets/svg/',
            layout: 'vertical',
            bust: true, //Cache busting
            render: {
                scss: { // Activate Sass output
                    template: joli.src + '/styles/sprite-tmpl/',
                    dest: '../' + joli.src + '/styles/_sprite'
                },
            }
        },
    }
};

gulp.task('svgSprite', function () {
    return gulp.src([joli.src + '/svg/common/**/*.svg', joli.src + '/svg/' + joli.environment + '/**/*svg'])
        .pipe(svgSprite(configSvgSprite))
        .on('error', function(error){
            console.log(error);
        })
        .pipe(gulp.dest('out'));
});

arijitpatrainstafreight

The npm package was last published 4 years ago and there seems to be a new update here. I am facing some issue with PhantomJS dependency on Apple M1 and seems like the new GitHub code here can solve it. When are you planning to release this as npm package?

benjarwar

I’m compiling a sprite and checking the file into my repo. But I’m getting inconsistent results. Sometimes, the xmlns attribute is added to each embedded <svg>, sometimes it is not. This is causing minor inconvenience, as it causes diffs in our pull requests when there aren’t actual changes.

I’ve referenced what you wrote here about the inline setting and tried adding inline: false to my config, but it doesn’t seem to solve the problem.

Here’s my pipe:

.pipe(svgSprite({
  mode: {
    defs: {
      dest: '.',
      prefix: '',
      sprite: 'sprite.svg'
    }
  },
  svg: {
    dimensionAttributes: false
  },
}))

Thanks in advance!

adamgilmour

Hi, just wondering if there’s an option to remove the <style> elements from the sprite.svg that’s compiled?

Ideally I’d like to grab all src .svg files, compile them into a sprite (which it current does great!) which then strips the styling to enable fill overwriting with css, when the sprite is used. Reason being, I’d also like to keep a base copy to include the original svg if needed with its original colours

THIS —-> <style>.fst0{fill:#29abe2}.fst1{fill:#37474f}.fst2{fill:#30c4ff}</style> <—- THIS
………
I’ve read through the documentation but can’t find what I’m looking for. Apologies if I’ve missed it.

Thanks

cortopy

Currently, the output for the svg sprite in symbol mode does not provide any styling. When file is included in the HTML , a big blank space is rendered on top of the page by the browser.

This is normal behaviour with svg sprites when no styling is added. So could ‘style=»display:none»‘ be added to the svg tag of the file? Adding it manually fixes the issue, but it has to be done every time the sprite is generated

Not sure if it’s an svg-sprite issue, so my apologies in advance if it is

NickolasDzR

my compiled file sprites.svg adds properties like
«:root>svg{display:none}:root>svg:target{display:block}»
svg{display:none} is why i cant use my sprites, they just dont show up when i add in my pug. And i tryed many of way to fix it but i couldn’t

can you say what is it and if you have any way to fix it i will glad.

patrykbura

QuipHop

Hi
I’m facing the problem when I need generate absolutely same file as default css, but with scss extension.
When i’m changing the render mode to scss it changes the paths in generated file to absolute. Is there a way to avoid it?
Thanks

{
    "dest": "src/",
    "mode": {
        "css": {
            "dest": "",
            "sprite": "./assets/icons/icons-sprite",
            "dimensions": true,
            "example": false,
            "prefix": ".%s",
            "render": {
                "scss": {
                    "dest": "./assets/stylesheets/sprites_all.scss",
                    "template": "./src/sprite-template.css"                
                }
            }
        }
    },
    "shape": {
        "id": {        
            "pseudo": "~"
        } 
    }
}

mearleycf

Here’s the gulp file.js:

// gulp-svg-sprite
svgSprite = require('gulp-svg-sprite');
let spriteConfig = {
  mode: {
    css: {
      render: {
        css: true
      }
    }
  }
};
gulp.task('sprites', function () {
  return gulp.src('**/.*.svg', {cwd: 'source/images'})
    .pipe(svgSprite(spriteConfig))
    .pipe(gulp.dest('source/test'));
});

// end gulp-svg-sprite

the directory is

  • foo
    —source
    —-images
    —gulpfile.js

Obviously there are more folders than that, but this is all that’s relevant to now.

I’ve tried doing ./source/images' as well and that does not work either.

banoodle

We just started using sonarcloud to run static code tests on our git commits.

It is complaining that the hyperlink inside the generated icons.html lacks a rel=noopener attribute which it considers a security hotspot.

Could this attribute be added to the next release? I notice this has been fixed in the svg-sprite repo.

Screen Shot 2022-06-01 at 2 04 16 PM

guoyunhe

In my project, I want to load SVG sprite in JS:

// sprite.js
module.exports = `<svg>...</svg>`;

Is it possible to add this feature?

Thanks!

yisibl

Have you considered using resvg-js instead of svg2png? resvg-js is almost the fastest and most compatible SVG library.

In some scenarios,resvg-js is even faster than sharp.

Benchmark

Running "resize width" suite...
  resvg-js(Rust):
    12 ops/s, ±22.66%   | fastest 🚀

  sharp:
    9 ops/s, ±64.52%    | 25% slower

  skr-canvas(Rust):
    7 ops/s, ±3.72%    | 41.67% slower

  svg2img(canvg and node-canvas):
    6 ops/s, ±16.94%    | slowest, 50% slower

image

See also https://github.com/RazrFalcon/resvg#svg-support

AdeptSEO

tcoldmf

$ gulp task_with_gulp_svg_sprite
(node:4064) UnhandledPromiseRejectionWarning
(node:4064) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:4064) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:4064) UnhandledPromiseRejectionWarning
(node:4064) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:4064) UnhandledPromiseRejectionWarning
(node:4064) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)
(node:4064) UnhandledPromiseRejectionWarning

tlkiong

deepakb2410

┌───────────────┬──────────────────────────────────────────────────────────────┐
│ High │ Denial of Service │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package │ css-what │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in │ >=5.0.1 │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ gulp-svg-sprite [dev] │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path │ gulp-svg-sprite > svg-sprite > svgo > css-select > css-what │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info │ https://npmjs.com/advisories/1754 │
└───────────────┴──────────────────────────────────────────────────────────────┘

corsairdnb

Does gulp-svg-sprite work with new Gulp version?
Now running plugin with any options gives such error:

[12:40:50] Error in plugin 'gulp-svg-sprite'
Message:
    Skipping "%s" (%s)
Details:
    domainEmitter: [object Object]
    domain: [object Object]
    domainThrown: false

I suppose this is due to deprecated status of gulp-util package.

binayatdelhi

I’m creating SVG sprite with following configuration which is working fine but it is removing «title» and «desc» of compiled SVG and I want to keep it. Is there any way I can stop it from uglify?

{
                    mode: {
                        css: {
                            render: {
                                css: {
                                    dest: 'svg-sprite.css'
                                }
                            },
                            bust: true,
                            dimensions: true,
                            prefix: ".",
                            dest: "./sprites/css"
                        },
                        symbol: true,
                        stack: true
                    },
                    shape: {
                        id: {
                            generator: function(name) {
                                return path.basename(name, '.svg');
                            }
                        },
                        dest: './sprites'
                    }
                }

Всем привет! В этой статье мы рассмотрим работу с svg спрайтами, как их создавать и подключать. Для начала разберемся что такое спрайт. Спрайт — это один большой графический файл, в котором объединены несколько небольших изображений. Спрайты были очень популярны, когда в качестве графики использовали растровые изображения. Создавали один большой файл, который содержит иконки, смайлики, логотипы, после чего через фоновое изображение в CSS и позиционирование показывали только ту часть графики, которая необходима. Это делается для уменьшения количества запросов к серверу, тем самым увеличивая скорость загрузки сайта. Svg спрайт аналогичен: в нем все наши svg изображение зашиты в один файл. Но работать с ним нужно немного иначе.

Как сделать svg спрайт

Что бы создать svg спрайт, создаем svg файл, например, sprite.svg. В него поместим корневой элемент svg. Далее вставляем svg код каждого изображения, обрамляя его тегом symbol. Всем элементам symbol назначаем уникальный id:

<svg>

    <symbol viewBox="0 0 448 512" id="icon1">
        {/* Иконка 1 */}
    </symbol>

    <symbol viewBox="0 0 448 512" id="icon2">
        {/* Иконка 2 */}
    </symbol>

    <symbol viewBox="0 0 448 512" id="icon3">
       {/* Иконка 3 */}
    </symbol>

</svg>

Как использовать svg спрайты

Что бы вывести любую иконку из svg спрайта, необходимо использовать тег svg, в котором через конструкцию use указываем ссылку на файл и id изображения:

<svg>
<use xlink:href="/sprite.svg#icon1"></use>
</svg>

Так же, можно просто скопировать весь svg спрайт в html страницу и использовать элемент use, передавая только id изображения.

CSS стили в svg спрайтах

Основным преимуществом использования svg спрайтов является возможность стилизовать иконки через CSS стили. Мы можем менять размер, цвет, фон иконок, а также — менять стили при наведении. Для этого в спрайте необходимо удалить атрибуты fill, stroke, style, так как они имеют большой приоритет. Далее просто в CSS задавать стили для svg элемента.

Пример использования svg спрайта

Давайте для примера использования svg спрайтов сделаем блок с иконками социальных сетей. Скачаем три svg иконки и сделаем из них спрайт. В итоге получим:

<svg>
        <symbol viewBox="0 0 448 512" id="instagram">
            <path d="M224.1 141c-63.6 0-114.9 51.3-114.9 114.9s51.3 114.9 114.9 114.9S339 319.5 339 255.9 287.7 141 224.1 141zm0 189.6c-41.1 0-74.7-33.5-74.7-74.7s33.5-74.7 74.7-74.7 74.7 33.5 74.7 74.7-33.6 74.7-74.7 74.7zm146.4-194.3c0 14.9-12 26.8-26.8 26.8-14.9 0-26.8-12-26.8-26.8s12-26.8 26.8-26.8 26.8 12 26.8 26.8zm76.1 27.2c-1.7-35.9-9.9-67.7-36.2-93.9-26.2-26.2-58-34.4-93.9-36.2-37-2.1-147.9-2.1-184.9 0-35.8 1.7-67.6 9.9-93.9 36.1s-34.4 58-36.2 93.9c-2.1 37-2.1 147.9 0 184.9 1.7 35.9 9.9 67.7 36.2 93.9s58 34.4 93.9 36.2c37 2.1 147.9 2.1 184.9 0 35.9-1.7 67.7-9.9 93.9-36.2 26.2-26.2 34.4-58 36.2-93.9 2.1-37 2.1-147.8 0-184.8zM398.8 388c-7.8 19.6-22.9 34.7-42.6 42.6-29.5 11.7-99.5 9-132.1 9s-102.7 2.6-132.1-9c-19.6-7.8-34.7-22.9-42.6-42.6-11.7-29.5-9-99.5-9-132.1s-2.6-102.7 9-132.1c7.8-19.6 22.9-34.7 42.6-42.6 29.5-11.7 99.5-9 132.1-9s102.7-2.6 132.1 9c19.6 7.8 34.7 22.9 42.6 42.6 11.7 29.5 9 99.5 9 132.1s2.7 102.7-9 132.1z"></path>
        </symbol>

        <symbol viewBox="0 0 448 512" id="facebook">
            <path d="m279.14 288 14.22-92.66h-88.91v-60.13c0-25.35 12.42-50.06 52.24-50.06h40.42V6.26S260.43 0 225.36 0c-73.22 0-121.08 44.38-121.08 124.72v70.62H22.89V288h81.39v224h100.17V288z"/>
        </symbol>

        <symbol viewBox="0 0 448 512" id="twitter">
           <path d="M459.37 151.716c.325 4.548.325 9.097.325 13.645 0 138.72-105.583 298.558-298.558 298.558-59.452 0-114.68-17.219-161.137-47.106 8.447.974 16.568 1.299 25.34 1.299 49.055 0 94.213-16.568 130.274-44.832-46.132-.975-84.792-31.188-98.112-72.772 6.498.974 12.995 1.624 19.818 1.624 9.421 0 18.843-1.3 27.614-3.573-48.081-9.747-84.143-51.98-84.143-102.985v-1.299c13.969 7.797 30.214 12.67 47.431 13.319-28.264-18.843-46.781-51.005-46.781-87.391 0-19.492 5.197-37.36 14.294-52.954 51.655 63.675 129.3 105.258 216.365 109.807-1.624-7.797-2.599-15.918-2.599-24.04 0-57.828 46.782-104.934 104.934-104.934 30.213 0 57.502 12.67 76.67 33.137 23.715-4.548 46.456-13.32 66.599-25.34-7.798 24.366-24.366 44.833-46.132 57.827 21.117-2.273 41.584-8.122 60.426-16.243-14.292 20.791-32.161 39.308-52.628 54.253z"/>
        </symbol>    
    </svg>

Далее создаем html файл, и делаем в нем небольшую разметку для вывода иконок. После этого копируем содержимое svg спрайта. В итоге получаем такую разметку:

<body>
    <ul class="social">
        <li class="social__item">
            <a href="" class="social__link">
                <svg class="social__icon">
                    <use xlink:href="#instagram"></use>
                </svg>
            </a>
        </li>
        <li class="social__item">
            <a href="" class="social__link">
                <svg class="social__icon">
                    <use xlink:href="#facebook"></use>
                </svg>
            </a>
        </li>
        <li class="social__item">
            <a href="" class="social__link">
                <svg class="social__icon">
                    <use xlink:href="#twitter"></use>
                </svg>
            </a>
        </li>
    </ul>

    <svg>
        <symbol viewBox="0 0 448 512" id="instagram">
            <path d="M224.1 141c-63.6 0-114.9 51.3-114.9 114.9s51.3 114.9 114.9 114.9S339 319.5 339 255.9 287.7 141 224.1 141zm0 189.6c-41.1 0-74.7-33.5-74.7-74.7s33.5-74.7 74.7-74.7 74.7 33.5 74.7 74.7-33.6 74.7-74.7 74.7zm146.4-194.3c0 14.9-12 26.8-26.8 26.8-14.9 0-26.8-12-26.8-26.8s12-26.8 26.8-26.8 26.8 12 26.8 26.8zm76.1 27.2c-1.7-35.9-9.9-67.7-36.2-93.9-26.2-26.2-58-34.4-93.9-36.2-37-2.1-147.9-2.1-184.9 0-35.8 1.7-67.6 9.9-93.9 36.1s-34.4 58-36.2 93.9c-2.1 37-2.1 147.9 0 184.9 1.7 35.9 9.9 67.7 36.2 93.9s58 34.4 93.9 36.2c37 2.1 147.9 2.1 184.9 0 35.9-1.7 67.7-9.9 93.9-36.2 26.2-26.2 34.4-58 36.2-93.9 2.1-37 2.1-147.8 0-184.8zM398.8 388c-7.8 19.6-22.9 34.7-42.6 42.6-29.5 11.7-99.5 9-132.1 9s-102.7 2.6-132.1-9c-19.6-7.8-34.7-22.9-42.6-42.6-11.7-29.5-9-99.5-9-132.1s-2.6-102.7 9-132.1c7.8-19.6 22.9-34.7 42.6-42.6 29.5-11.7 99.5-9 132.1-9s102.7-2.6 132.1 9c19.6 7.8 34.7 22.9 42.6 42.6 11.7 29.5 9 99.5 9 132.1s2.7 102.7-9 132.1z"></path>
        </symbol>

        <symbol viewBox="0 0 448 512" id="facebook">
            <path d="m279.14 288 14.22-92.66h-88.91v-60.13c0-25.35 12.42-50.06 52.24-50.06h40.42V6.26S260.43 0 225.36 0c-73.22 0-121.08 44.38-121.08 124.72v70.62H22.89V288h81.39v224h100.17V288z"/>
        </symbol>

        <symbol viewBox="0 0 448 512" id="twitter">
           <path d="M459.37 151.716c.325 4.548.325 9.097.325 13.645 0 138.72-105.583 298.558-298.558 298.558-59.452 0-114.68-17.219-161.137-47.106 8.447.974 16.568 1.299 25.34 1.299 49.055 0 94.213-16.568 130.274-44.832-46.132-.975-84.792-31.188-98.112-72.772 6.498.974 12.995 1.624 19.818 1.624 9.421 0 18.843-1.3 27.614-3.573-48.081-9.747-84.143-51.98-84.143-102.985v-1.299c13.969 7.797 30.214 12.67 47.431 13.319-28.264-18.843-46.781-51.005-46.781-87.391 0-19.492 5.197-37.36 14.294-52.954 51.655 63.675 129.3 105.258 216.365 109.807-1.624-7.797-2.599-15.918-2.599-24.04 0-57.828 46.782-104.934 104.934-104.934 30.213 0 57.502 12.67 76.67 33.137 23.715-4.548 46.456-13.32 66.599-25.34-7.798 24.366-24.366 44.833-46.132 57.827 21.117-2.273 41.584-8.122 60.426-16.243-14.292 20.791-32.161 39.308-52.628 54.253z"/>
        </symbol>    
    </svg>
</body>

Теперь добавим немного стилей:

body{
    background-color: #333;
}
.social {
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    list-style-type: none;
    width: 300px;
    padding: 10px 20px 10px 20px;
    margin: 0 auto;
    border-radius: 30px;
}
.social__link {
    fill: #333;
}
.social__link:hover{
    fill: #E67E22;
}
.social__icon{
    fill: inherit;
    height: 60px;
    width: 60px;
    transition: .2s;
}

Здесь мы выравниваем наши иконки по горизонтали, задаем размеры и цвета. Цвет иконки в обычном состоянии и при наведении задаем с помощью свойства fill родительскому элементу, а у самой иконки наследуем это свойство. Таким образом получаем такую верстку:

See the Pen
Svg sprite by astupakov (@astupakov)
on CodePen.

Использование gulp для автоматической генерации svg спрайтов

Собирать спрайты вручную — очень трудоемкая работа. Поэтому создание svg спрайтов можно автоматизировать. Для этого мы будем использовать gulp и плагин gulp-svg-sprite.

Идея заключается в том, что мы просто перемещаем все свои svg файлы в одну папку, а gulp захватит все эти файлы и сгенерирует спрайт автоматически. Рассмотрим вкратце как это реализовать.

Устанавливаем плагин gulp-svg-sprite:

npm install gulp-svg-sprite –S

В файле gulpfile.js создаем таск для генерации спрайта:

const gulp = require('gulp');
const svgSprite = require('gulp-svg-sprite');

function svgsprite(){
    let config = {
        shape: {
            dimension: {
                maxWidth: 500,
                maxHeight: 500
            },
            spacing: {
                padding: 0
            },
            transform: [{
                "svgo": {
                    "plugins": [
                        { removeViewBox: false },
                                { removeUnusedNS: false },
                                { removeUselessStrokeAndFill: true },
                                { cleanupIDs: false },
                                { removeComments: true },
                                { removeEmptyAttrs: true },
                                { removeEmptyText: true },
                                { collapseGroups: true },
                                { removeAttrs: { attrs: '(fill|stroke|style)' } }
                    ]
                }
            }]
        },
        mode: {
            symbol: {
                dest : '.',
                sprite: 'sprite.svg'
            }
        }
    };

    return gulp.src("src/img/svgIcons/*.svg")      
        .pipe(svgSprite(config)).on('error', function(error){ console.log(error); })
        .pipe(gulp.dest("dist/img/ "));
}

exports.svgsprite = svgsprite;

В начале мы создаем переменную config с настройками для плагина, в которой говорим, что спрайт будет создаваться через элемент symbol и называется spite.svg. Так же, удаляем ненужные атрибуты и оптимизируем графику.

Далее указываем, что файлы лежат в папке src/img/svgIcons/, а создавать спрайт нужно в папку dist/img/. Плагин автоматически генерирует id для каждого изображения из его имени, по этому иконкам нужно давать осмысленные названия. Дале используем этот спрайт так как мы делали это раньше.

Использование миксинов для создания svg спрайтов

Каждый раз вставлять спрайт через svg не очень удобно. Если вы используете какой-то html препроцессор, то эту задачу можно упростить, создав некий миксин для вставки спрайта. Рассмотрим такую реализацию на примере шаблонизатора nunjucks.

В nunjucks для подобных задач используются макросы. Для начала создаем отдельный файл для всех макросов _macro.html. В нем создаем макрос svgIcon для вывода изображений из svg спрайта:

{% macro svgIcon(icon, class = '', path = '/assets/img/sprite.svg') %}
    <svg class="svg-icon {{ class }}">
      <use xlink:href="{{path}}#{{ icon }}"></use>
    </svg>
{% endmacro %}

Этот макрос принимает 3 параметра:

  • Id изображения;
  • Произвольный класс изображения. По умолчанию значение пустое. Для удобства каждой иконке мы добавляем класс svg-icon;
  • Путь к файлу svg спрайта. По умолчанию принимает значение, которое установили в настройка gulp файла для генерации спрайта.

Далее необходимо импортировать этот файл в основной документ:

{% import ./_macro.html" as macro %}

Теперь макрос готов к использованию. Ко всем макросам можно обратится через переменную macro. Рассмотрим пару примеров вызова:

{{macro.svgIcon('instagram')}}
{{macro.svgIcon('instagram', ’social__icon’)}}
{{macro.svgIcon('instagram', ’social__icon’, ‘assets/img/socialSprite.svg’)}}

В первом примере мы просто выводим иконку, у которой id равно instagram. Во втором варианте добавляется класс social__icon. В третьем примере мы изменяем путь к спрайту.

Заключение

На этом пока все. Мы рассмотрели работу с svg спрайтами. Это очень удобный вариант работы с графикой и обладает рядом преимуществ:

  • Использует один http запрос;
  • Есть возможность изменять стили через CSS;
  • Не теряется качество при масштабировании;
  • Довольно прост в реализации.

Понравилась статья? Поделить с друзьями:
  • Error in plugin gulp sass
  • Error in plugin gulp postcss
  • Error in plugin gulp babel
  • Error in plots display expecting plot structure but received
  • Error in plot3d first argument must be either in standard or parametric form