Svg-sprite-loader: Get viewBox for SVG tag

Created on 16 Apr 2016  路  11Comments  路  Source: JetBrains/svg-sprite-loader

It seems (and I might be wrong) that SVG requires either specific width and height or viewBox and a single dimension to scale properly and preserve ratio.

Here's a a demo with code that's similar to what this loader generates:
http://codepen.io/elado/pen/GZdJZG?editors=1100

If no dimension or viewBox supplied, SVG defaults to 300x150 which is a browser default.
In the demo, the ones without the viewBox and only height get the 300px width.
Even though viewBox is defined on the <symbol>, the <svg><use ...> that will contain it won't grab it.

Is there a way to somehow import the viewBox to the SVG, or another workaround?

Most helpful comment

All 11 comments

@elado I can preserve width and height attributes from original image in symbol

@kisenka I don't think that helps. Seems like <svg> tag has to have viewBox if only one of the dimensions is defined. (which is important if I have multiple icons in a row and I want them the same height).

I currently solved this with another weird loader I created as a local module:

module.exports = function (source) {
  this.cacheable()
  var m = source.match(/<svg[\s\S]+?viewBox="(.+?)"[\s\S]+?>/)
  return `module.exports = ${JSON.stringify(m ? m[1] : null)}`
}

and in my <svg> tag:

<svg viewBox={require(`!svg-viewbox-loader!path/to/icon.svg`)} ...>
  <use xlinkHref={require(`path/to/icon.svg`)} />
</svg>

@elado I think that conceptually it must be something like this:

<svg viewBox={require(`path/to/icon.svg`).viewBox} ...>
  <use xlinkHref={require(`path/to/icon.svg`).xlinkHref} />
</svg>

Such loader API will be convenient what you think?

I think it'll be a great addition to this loader. It can output an object if some param in the loader query is present (for backwards compatibility)

If you have an es6 version, you can output the xlinkHref as default and the viewBox in a separate export. Automatic backwards compatibility.

I think https://github.com/kisenka/svg-sprite-loader/blob/master/lib/svg-document.js needs to implement a getViewbox which gets it from cheerio either directly or via width/height, and then this gets passed to sprite.add() via a third parameter.

+1

+1

@creative-eye
@w3apps

Hey guys [email protected] with new runtime module is on the way, please read about it here #91 and take part in discussion/voting.

Now it's possible to get viewBox of the symbol, see new version readme.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sqal picture sqal  路  4Comments

evgenyrodionov picture evgenyrodionov  路  4Comments

fruchtose picture fruchtose  路  5Comments

edaena picture edaena  路  7Comments

alxpsr picture alxpsr  路  4Comments