cascornelissen / svg-spritemap-webpack-plugin Goto Github PK
View Code? Open in Web Editor NEWSVG spritemap plugin for webpack
License: MIT License
SVG spritemap plugin for webpack
License: MIT License
Hello,
I was wondering how I could disable the title of an generated icon ?
I can't find an option to disable the auto generating of a title.
My icons are constructed like below. The title "toevoegen" is only active when you over over a part of the icon that has no content. Else the title "add_circle" is displayed.
<a href="/customer-service/patients/new/" title="Toevoegen">
<svg class="icon " }}="">
<use xlink:href="/dist/sprites.svg#add_circle"></use>
</svg>
</a>
I have changed this in my npm folder. This seems to be working well. Mind you this is my first time I changed a npm package.
function SVGSpritemapPlugin(options) {
// Merge specified options with default options
this.options = merge({
src: '**/*.svg',
svgo: {},
glob: {},
prefix: 'sprite-',
gutter: 2,
filename: 'spritemap.svg',
chunk: 'spritemap',
deleteChunk: true,
svg4everybody: false,
generateTitle: true <--- Added
}, options, {
svgo: {
plugins: [{
cleanupIDs: false
}]
}
});
}
// Generate a title or not ?
if( options.generateTitle == true ) { <--- Added
// Make sure we don't overwrite the existing title
var hasTitle = false;
for ( var i = 0; i < svg.childNodes.length; i++ ) {
if ( svg.childNodes[i].tagName && svg.childNodes[i].tagName.toLowerCase() === 'title' ) {
var hasTitle = true;
}
}
// Add title for improved accessibility
if ( !hasTitle ) {
var title = XMLDoc.createElement('title');
title.appendChild(XMLDoc.createTextNode(id.replace(options.prefix, '')));
symbol.appendChild(title);
}
}
The $sizes
variable in the generated output scss is colliding with the same variable name used by Bootstrap 4.
Is there a way to change variable names or at least scope the variables to a namespaces in a minor release?
Add some kind of options like alwaysWriteToDisk
to generated output of svg-sprite to disk. This is very useful if you want to pick up the output with another middleware.
The following error occurs when trying to use this plugin with Webpack 4.
/my/project/path/node_modules/svg-spritemap-webpack-plugin/svg-spritemap.js:62
sourceChunk.files.push(filename);
^
TypeError: Cannot read property 'files' of undefined
at additionalChunkAssets (/my/project/path/node_modules/svg-spritemap-webpack-plugin/svg-spritemap.js:62:25)
at SyncHook.eval [as call] (eval at create (/my/project/path/node_modules/tapable/lib/HookCodeFactory.js:17:12), <anonymous>:7:1)
at SyncHook.lazyCompileHook [as _call] (/my/project/path/node_modules/tapable/lib/Hook.js:35:21)
at hooks.optimizeTree.callAsync.err (/my/project/path/node_modules/webpack/lib/Compilation.js:935:37)
at _err0 (eval at create (/my/project/path/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:11:1)
at _async2.default.forEach.err (/my/project/path/node_modules/extract-text-webpack-plugin/dist/index.js:281:11)
at /my/project/path/node_modules/async/dist/async.js:473:16
at iteratorCallback (/my/project/path/node_modules/async/dist/async.js:1050:13)
at /my/project/path/node_modules/async/dist/async.js:958:16
at _async2.default.forEach.err (/my/project/path/node_modules/extract-text-webpack-plugin/dist/index.js:259:13)
at /my/project/path/node_modules/async/dist/async.js:473:16
at iteratorCallback (/my/project/path/node_modules/async/dist/async.js:1050:13)
at /my/project/path/node_modules/async/dist/async.js:958:16
at compilation.rebuildModule.err (/my/project/path/node_modules/extract-text-webpack-plugin/dist/index.js:246:26)
at callback (/my/project/path/node_modules/webpack/lib/Compilation.js:775:35)
at processModuleDependencies.err (/my/project/path/node_modules/webpack/lib/Compilation.js:797:5)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
Hi, first of all thanks for the great plugin, working with SVG icons is much easier with it.
Today, I've decided to try to use generated sprite in CSS background property.
This technique is supported in most modern browsers, and you can see an example here –
http://jsfiddle.net/simurai/7GCGr/
Unfortunately, it seems that the current generated sprite output (specifically, <symbol>
element) does not support this functionality.
When I add a style declaration like background: url('/icons-sprite.svg#plus') no-repeat;
the whole sprite is included, not a single fragment. And when I try to limit it's size, the sprite is scaled as a whole as well.
I was wondering if it's possible to extend current configuration options to support the kind of output needed to allow using svg fragments from external sprites in CSS.
This is an example of svg sprite which allows to included separate fragments – http://xn--dahlstrm-t4a.net/tmp/sharp-icons/svg-icon-target.svg
I'm sorry for not providing more constructive feedback, and I hope I'll have time to investigate the issue further in future. But since you obviously know more about SVGs that I do, I just wanted to plant this thought and maybe discuss it a bit more.
It is entirely possible that I am missing something and this should be working out of the box.
I am using 3.0.0
version with webpack 4.
Thanks.
Edit:
I've decided to add my current config just in case
new SVGSpritemapPlugin('./src/assets/icons/**/*.svg', {
output: {
filename: 'icons-sprite.svg',
svg4everybody: false,
},
sprite: {
prefix: false,
},
Edit2:
Upon further investigation, I've figured out that the only thing missing from output in order to be able to use svg fragments in CSS is style tag which could look similar to the following:
<style>
symbol { display: none }
symbol:target { display: inline }
</style>
Looking at the docs, there's no way to include such tag in output file, right?
Also, dimensions of fragments included in CSS seem to be affected by width
and height
attributes on <use>
element in the sprite.
Here's the same icon used as background with the following properties
background-image: url('/icons-sprite.svg#alert');
background-size: 100px;
with <use xlink:href="#alert" width="28" height="24"/>
:
and with <use xlink:href="#alert" />
:
As you can see, when attributes are in place, icon is much smaller than expected size. Also, removal of width/height doesn't seem to have any negative effect (I've checked usage in HTML and CSS).
I'd like to hear you thoughts on the matter.
for example for people who wants to use a custom version of it with my own plugins.
or custom version
Hey, I use create-react-app to start my project. And the webpack config is shown blow:
output: {
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
// Add module names to factory functions so they appear in browser profiler.
new webpack.NamedModulesPlugin(),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new SVGSpritemapPlugin(),
]
But when I use npm start
, there is no spritemap.svg in my workspace. If I set path
like path.join(__dirname, '../src/')
, there is no help either. I don't know what's wrong...
version: 1.1.1
webpack version: 3.8.1
Hi,
I'm trying to get multiple sprites working with scss. The files get generated, but when I import them in my scss file, the last imported one overrules the other ones of course.
plugins: [
new SVGSpritemapPlugin({
src: 'gfx/svg/common/*.svg',
filename: 'gfx/common-sprite.svg',
prefix: 'common-sprite-',
gutter: 2,
styles: 'src/css/_common_sprite.scss'
}),
new SVGSpritemapPlugin({
src: 'gfx/svg/pdp/*.svg',
filename: 'gfx/pdp-sprite.svg',
prefix: 'pdp-sprite-',
gutter: 2,
styles: 'src/css/_pdp_sprite.scss'
})
]
@import "common_sprite";
@import "pdp_sprite";
So my question is, is it possible to target specific sprites in scss?
Maybe like this?
@include sprite('icon-name', 'sprite-name);
Thank you very much for this nice plugin! :)
Hello, I need to put two routes with different files, Is there a way to do this?.
Thanks a lot!
If using the styles option of your plugin, the generated css contains the icons es embedded data in the background url. I assume it is like this, because safari did not support css svg fragment identifiers until now. (https://css-tricks.com/svg-fragment-identifiers-work/#article-header-id-3) That has the downside, that if I use the same icon on 5 places in my code, the data for the icon is embedded 5 times. Of course I can try to use a post css tool to clean it up..
The recent safari update (safari 11.1 / safari IOS 11.3) added support for those fragement identifiers, see https://caniuse.com/#feat=svg-fragment
Therefore, it would be nice, if there would be an option to choose, if the css should contain the icons embedded in the url or just the url to the file, as it is for the html way of using it.
This may likely be a Webpack question, but:
How would we reference a fragment of the spritemap directly in any CSS file? ie
.thingy {
content: url('spritemap.svg#sprite-thingy');
}
If you set sprite in background image and pictrure doesn't display. Add to style-formaters/scss.js this string svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
It help me to display svg images on page in latest version Google Chrome and Firefox
The documentation referenced on READ.md https://github.com/cascornelissen/svg-spritemap-webpack-plugin/blob/master/docs/options.md
is for the next (versions 3.xxx). Can you please make this clear in the documentation? It's otherwise very confusing.
Thanks.
─┬ [email protected]
└── [email protected]
const mix = require('laravel-mix');
const SVGSpritemapPlugin = require('svg-spritemap-webpack-plugin');
// Set up the spritemap plugin
mix.webpackConfig({
plugins: [
new SVGSpritemapPlugin({
src:'assets/svg/icons/*.svg',
filename: '/svg/icons.svg',
prefix: '',
svg4everybody: true,
svgo: {
removeTitle: true,
removeStyleElement: true,
cleanupNumericValue: true,
},
})
]
});
// Adapt laravel-mix webpack config to better handle svg images.
Mix.listen('configReady', (webpackConfig) => {
// Add separate svg loader
webpackConfig.module.rules.push({
test: /\.(svg)$/,
include: /assets\/svg/,
loaders: [
{
loader: 'file-loader',
options: {
name: 'svg/[name].[ext]?[hash]',
publicPath: Config.resourceRoot
}
},
{
loader: 'img-loader',
options: Config.imgLoaderOptions
}
]
});
// Exclude local 'svg' folder from font loader
let fontLoaderConfig = webpackConfig.module.rules.find(rule => String(rule.test) === String(/\.(woff2?|ttf|eot|svg|otf)$/))
fontLoaderConfig.exclude = /(assets\/svg)/;
});
Error: ValidationError: "src" is not allowed. "filename" is not allowed. "prefix" is not allowed. "svg4everybody" is not allowed. "svgo" is not allowed
Config of:
plugins: [
new SVGSpritemapPlugin(
path.resolve(./svgicon/svg/**/*.svg'),
{
styles: {
filename: 'icons.css',
},
output: {
svg4everybody: true,
svgo: true,
},
}
),
],
results in command line output of:
WARNING in svg-spritemap-webpack-plugin
Variables are not supported when using CSS
Couldn't extract sprites.css for version ^1.0.0, could you help make it compatible on that?
var path = require('path')
var merge = require('webpack-merge')
var webpack = require('webpack')
var config = require('../config')
var utils = require('./utils')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
var StyleLintPlugin = require('stylelint-webpack-plugin')
var SVGSpritemapPlugin = require('svg-spritemap-webpack-plugin');
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
var isDev = process.env.NODE_ENV === 'development'
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: isDev
? config.dev.assetsPublicPath
: config.build.assetsPublicPath
},
resolve: {
extensions: ['.js', '.json'],
},
module: {
rules: [
{
test: /\.js/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.(jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
}
]
},
plugins: [
...utils.pageFile(isDev),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css')
}),
new StyleLintPlugin({
configFile: '.stylelintrc.json'
}),
new SVGSpritemapPlugin({
src: resolve('src/svg-icon/*.svg'),
filename: 'sprite.svg',
prefix: '',
svg4everybody: true,
styles: 'src/styles/_sprites.scss'
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: {
safe: true
}
}),
]
}
Hi, I trying to migrate from gulp to webpack and I need to generate svg sprite. But when sprite is generated, settings doesn't not affect the outcome. I have svg named logo.svg
, and I expect symbol
with id icon-logo
, but I get:
<symbol id="a" viewBox="0 0 512 512">...
Run at MacOS High Sierra 10.13.4, webpack version 4.8.0, config:
new SVGSpritemapPlugin({
src: 'assets/svg/**/*.svg',
filename: '../svg/sprite.svg',
prefix: 'icon-',
svgo: {
plugins: [
{
removeTitle: false,
minify: false,
removeXMLNS: true,
},
],
},
}),
Using it with Rails Webpacker environment results in error:
TypeError: Cannot read property 'entryOption' of undefined
at SVGSpritemapPlugin.apply (/some-project/node_modules/svg-spritemap-webpack-plugin/lib/index.js:73:24)
at Compiler.apply (/some-project/node_modules/tapable/lib/Tapable.js:375:16)
at webpack (/some-project/node_modules/webpack/lib/webpack.js:33:19)
at startDevServer (/some-project/node_modules/webpack-dev-server/bin/webpack-dev-server.js:367:16)
at processOptions (/some-project/node_modules/webpack-dev-server/bin/webpack-dev-server.js:350:5)
at Object.<anonymous> (/some-project/node_modules/webpack-dev-server/bin/webpack-dev-server.js:495:1)
at Module._compile (module.js:624:30)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
...with this config:
const { environment } = require('@rails/webpacker');
const SVGSpritemapPlugin = require('svg-spritemap-webpack-plugin');
environment.plugins.prepend(
'SVGSpritemapPlugin',
new SVGSpritemapPlugin()
);
module.exports = environment;
Any ideas why?
We love your plugin. Thanks for programming. Unfortunately, we can not yet upgrade our projects to the current Webpack version. Therefore we have to use plugin version 1.x, which doesn't yet support the 'style' option.. Is it possible to integrate the style support in this version as well?
Subj
Currently this plugin supports using globs to select SVGs from nested folder structures, which is awesome!
It would be great to allow the sprite.prefix
option to accept a function which can take the glob as an argument and produce a dynamic prefix, which would be helpful for nested folder structures.
Example assets:
assets/
- banners/
- home.svg
- contact.svg
- logos/
- black.svg
- white.svg
Glob transformer
const prefix = (glob) => {
const parts = glob.split('/');
return parts.splice(1, parts.length - 2).join('-')
};
Options:
{
...
sprite: {
prefix,
},
...
}
Produces:
spritemap.svg#banners-home
spritemap.svg#banners-contact
spritemap.svg#logos-black
spritemap.svg#logos-white
Is there currently a way to automatically add display='none'
to the svg sprite? Otherwise it needs to be added manually.
Hi @cascornelissen,
fist of all thanks a lot for these plugin 🎉
I just tried out the new feature which allows you to define a color for the sprite mixin:
@import '~svg-spritemap-webpack-plugin/sprites';
@include sprite('close', (
color: '#fff'
));
But it don't work for me.
I tested it with version 2.7.1
and 3.0.0-rc.2
.
Thanks in advance
Repro case: DreadBoy@f8f0a11
Badge was downloaded from https://commons.wikimedia.org/wiki/File:Get_it_on_Google_play.svg
Repro steps:
http-server
(or anything similar) in example's rootI don't see gradients in Play's logo because they were removed from spritemap. I tried turning off Svg4Everybody and SVGO but it didn't help. Do you have any idea why they are being removed. SVG renders fine if I open it as is.
"svg-spritemap-webpack-plugin": "^3.2.1",
// SVG Sprites config
mix.webpackConfig({
plugins: [
new SVGSpritemapPlugin(
'resources/img/svg-icons/**/*.svg',
{
output: {
filename: 'img/icon-sprite.svg',
svg4everybody: true,
svgo: {
removeAttrs: true,
removeStyleElement: true,
}
}
}
)
],
});
I've tried changing the value of the filename
, e.g.:
filename: 'something.svg',
However, it Webpacker's manifest.json
it appears as:
"spritemap.svg": "/packs/something.svg",
As a matter of fact, this asset_pack_path('something.svg')
doesn't work and most importantly it's not possible to have multiple sprite files. Not sure if it's a problem of the plugin though.
After upgrading to 3.0.1 (from 3.0.0#master), I'm seeing the following error. Commenting out the svg-spritemap-webpack-plugin usage eliminates it, so it looks like it's the new version. :( The following stack trace backs that up.
node: 10.13.0
webpack: 4.27.1
svg-spritemap-webpack-plugin: 3.0.1
os: windows 10
(node:84124) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'providedExports' of undefined
at fnModule (C:\Users\NOPE\myproject\dls\node_modules\webpack\lib\Stats.js:586:58)
at Array.map (<anonymous>)
at obj.chunks.compilation.chunks.map.chunk (C:\Users\NOPE\myproject\node_modules\webpack\lib\Stats.js:658:8)
at Array.map (<anonymous>)
at Stats.toJson (C:\Users\NOPE\myproject\node_modules\webpack\lib\Stats.js:616:36)
at StatsWriterPlugin.emitStats (C:\Users\NOPE\myproject\node_modules\webpack-stats-plugin\lib\stats-writer-plugin.js:72:40)
at AsyncSeriesHook.eval [as callAsync] (eval at create (C:\Users\NOPE\myproject\node_modules\tapable\lib\HookCodeFactory.js:32:10), <anonymous>:8:17)
at AsyncSeriesHook.lazyCompileHook (C:\Users\NOPE\myproject\node_modules\tapable\lib\Hook.js:154:20)
at Compiler.emitAssets (C:\Users\NOPE\myproject\node_modules\webpack\lib\Compiler.js:363:19)
at onCompiled (C:\Users\NOPE\myproject\node_modules\webpack\lib\Compiler.js:231:9)
at hooks.afterCompile.callAsync.err (C:\Users\NOPE\myproject\node_modules\webpack\lib\Compiler.js:552:14)
at AsyncSeriesHook.eval [as callAsync] (eval at create (C:\Users\NOPE\myproject\node_modules\tapable\lib\HookCodeFactory.js:32:10), <anonymous>:33:1)
at AsyncSeriesHook.lazyCompileHook (C:\Users\NOPE\myproject\node_modules\tapable\lib\Hook.js:154:20)
at compilation.seal.err (C:\Users\NOPE\myproject\node_modules\webpack\lib\Compiler.js:549:30)
at AsyncSeriesHook.eval [as callAsync] (eval at create (C:\Users\NOPE\myproject\node_modules\tapable\lib\HookCodeFactory.js:32:10), <anonymous>:6:1)
at AsyncSeriesHook.lazyCompileHook (C:\Users\NOPE\myproject\node_modules\tapable\lib\Hook.js:154:20)
at hooks.optimizeAssets.callAsync.err (C:\Users\NOPE\myproject\node_modules\webpack\lib\Compilation.js:1323:35)
at _err3 (eval at create (C:\Users\NOPE\myproject\node_modules\tapable\lib\HookCodeFactory.js:32:10), <anonymous>:26:1)
at compilation.hooks.optimizeAssets.tapAsync (C:\Users\NOPE\myproject\node_modules\svg-spritemap-webpack-plugin\lib\index.js:245:32)
at _err2 (eval at create (C:\Users\NOPE\myproject\node_modules\tapable\lib\HookCodeFactory.js:32:10), <anonymous>:22:1)
at SVGOptimizer.optimize.then (C:\Users\NOPE\myproject\node_modules\svg-spritemap-webpack-plugin\lib\index.js:236:32)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:84124) 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:84124) [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.
All paths in my output have id="a". When using the sprite map in chrome, each symbol uses the first found path with id="a", instead od the closest id="a". This causes all svg's to use the same path.
If I use Webpack in watch mode and change one of source .svg, Webpack doesn't rebuild app. Is this intended? If it is, is there a way to trick Webpack to watch for changes in source files?
It seems that my SVGO options are being overridden because of how cleanupIDs: false
plugin is merged into the options.
new SVGSpritemapPlugin({
src: './src/svg/icons/**/*.svg',
filename: 'svg/icons-sprite.svg',
svgo: {
plugins: [{
convertColors: {currentColor: '#030303'}
}],
},
}),
After upgrading to v3.3.1, the plugin throws the following error when building with webpack:
C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\webpack-cli\bin\cli.js:265
throw err;
^
Error: must provide pattern
at new GlobSync (C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\glob\sync.js:31:11)
at Function.globSync [as sync] (C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\glob\sync.js:26:10)
at directories.inputOptions.patterns.reduce (C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\svg-spritemap-webpack-plugin\lib\index.js:321:38)
at Array.reduce (<anonymous>)
at SVGSpritemapPlugin.updateDependencies (C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\svg-spritemap-webpack-plugin\lib\index.js:319:50)
at SyncHook.eval [as call] (eval at create (C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:7:1)
at SyncHook.lazyCompileHook (C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\tapable\lib\Hook.js:154:20)
at webpack (C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\webpack\lib\webpack.js:51:30)
at processOptions (C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\webpack-cli\bin\cli.js:256:16)
at yargs.parse (C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\webpack-cli\bin\cli.js:373:3)
at Object.parse (C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\yargs\yargs.js:567:18)
at C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\webpack-cli\bin\cli.js:49:8
at Object.<anonymous> (C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\webpack-cli\bin\cli.js:375:3)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (C:\Users\Croccifixio\Desktop\playground\sprite-map-pr\node_modules\webpack\bin\webpack.js:156:2)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ build: `webpack`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Croccifixio\AppData\Roaming\npm-cache\_logs\2019-05-17T22_44_12_123Z-debug.log
I have created a repo where the error can be reproduced. The following webpack config is used:
const SVGSpritemapPlugin = require('svg-spritemap-webpack-plugin')
module.exports = {
entry: './index.js',
plugins: [
new SVGSpritemapPlugin('icons/*.svg', {
output: {
filename: "dist/icons.svg",
},
}),
],
}
Downgrading to v3.3.0 causes the build to proceed without any errors.
Windows version: 10.0.17763 Build 17763
Node version: 10.15.3
svg-spritemap-webpack-plugin version: 3.3.1
webpack version: 4.31.0
Hey,
Would be awesome to have a HTML example page generator like https://github.com/jkphl/svg-sprite. So you can preview and snippet the icons quickly.
Thanks!
If you try to add an SVG file without a width
, height
and viewBox
element, the script returns an error exactly where it should report the missing file.
The file
variable is used in a previous Promise function, but is no longer available (since the code has gone to a new then
node).
I might write a PR for this, but don't have the time right now.
A hotfix is to replace this line with a return;
statement, but it's not helping anyone solve the issue.
Hey,
first of all thanks for the great plugin!
I missed the color prop in the mixin, so I added the fill prop in the formatter files & icon.scss. Are there any plans to integrate the color, size prop to the scss/less in the future?
Thats what I've done, it works perfectly for me:
scss-formatter.js:
svg.setAttribute('fill', '%fill%');
styles.scss:
@mixin sprite($name, $fill: #000) {
$sprite: str-replace(map-get($sprites, $name),'%25fill%25',$fill);
background: url($sprite) center no-repeat;
}
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
I only changed the scss cause I only use scss in my proj. Maybe I will integrate the size in the sprite mixin as well.
BR
Tillmann
When I run svg's through this plugin without the attribute viewBox set, the output of the particular svg will contain the viewBox
attribute set to NaN
. I often use svg's with width and height set, instead of viewBox.
Most of the time I solved it by setting the viewBox
. In the example below I changed width="357" height="357"
to viewBox="0 0 357 357"
, but this shouldn't be necessary.
Example of svg before webpack:
<svg xmlns="http://www.w3.org/2000/svg" width="357" height="357">
<path fill="#000" d="M357 35.7L321.3 0 178.5 142.8 35.7 0 0 35.7l142.8 142.8L0 321.3 35.7 357l142.8-142.8L321.3 357l35.7-35.7-142.8-142.8z"/>
</svg>
Example of symbol after webpack:
<symbol id="sprite-cancel-test" viewBox="NaN">
<title>cancel-test</title>
<path d="M357 35.7L321.3 0 178.5 142.8 35.7 0 0 35.7l142.8 142.8L0 321.3 35.7 357l142.8-142.8L321.3 357l35.7-35.7-142.8-142.8z"/>
</symbol>
<use xlink:href="#sprite-cancel-test" width="357" height="357"/>
When using the svg sprite in sass as background, the container dimensions or background size need to be used to scale the svg. Often the svg needs to be used in ins original dimensions, so it would be really helpful to be able to access these in sass. Could you consider changing the generated sprite object like so:
$sprites: (
'mySVG': (
svg: "data:image/svg+xml,%3csvg xmlns...",
width: 14.5,
height: 5
)
);
The mixin would need to be changed like so:
@mixin sprite($name) {
$obj: map-get($sprites, $name);
$sprite: map-get($obj, svg);
background: url($sprite) center no-repeat;
}
That would add the possibility to overwrite the mixin with a custom one that uses the original dimensions of the svg:
@mixin sprite($name) {
$obj: map-get($sprites, $name);
$sprite: map-get($obj, svg);
background: url($sprite) center no-repeat;
background-size: map-get($obj, width)px map-get($obj, height)px;
}
You could also consider adding an optional parameter to the mixin that sets the svg to it's original size.
Thanks!
I am running "svg-spritemap-webpack-plugin": "^2.0.0-rc.4" on webpack 4.1.1. My config for this plugin is:
new SVGSpritemapPlugin({
src: 'assets/gfx/*.svg',
filename: 'spritemap.[contenthash].svg',
prefix: 'fablr-',
}),
But when this is active, all other files (JS, CSS, etc) are not emitted anymore. So it's unusable for me. I'm not able to see what happens, except that everything is back to normal when I comment out SVGSpritemapPlugin. Any pointers?
The code below outputs an SVG that is minified, with double title attributes and no prefix. Tried on version 1.0.3
new SVGSpritemapPlugin({
src:path.resolve(__dirname,basePath + '/img/icons-svg/**/*.svg'),
filename: 'img/sprite.svg',
svgo:{
removeTitle: false,
minify:false,
removeXMLNS:true,
prefix: 'svg-icon-',
},
svg4everybody:true,
}),
webpack file
const SVGSpritemapPlugin = require('svg-spritemap-webpack-plugin');
...
plugins: [
new ExtractTextPlugin('styles.css'),
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, 'resources/img'),
to: path.resolve(__dirname, 'public/dist/images')
}
]),
new SVGSpritemapPlugin({
// src: path.resolve(__dirname, 'resources/icons'),
// filename: 'sprites.svg'
})
]
This is the firts time I use webpack. Added the const at the top and updated the plugin array. After that trying to run webpack, but I end up with a error below. Added various configurations, same result.
I get the following error. Using webpack 3.11.0.
node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development webpack
/var/www/......../node_modules/webpack/bin/webpack.js:348
throw err;
^
TypeError: Cannot read property 'entryOption' of undefined
The webpack uglify plugin fails if you run webpack -p
Error message:
ERROR in UglifyEsPlugin - spritemap.svg
{"message":"Unexpected token: operator (<)","filename":"spritemap.svg","line":1,"col":0,"pos":0}
Any idea how to solve this issue?
Changing webpack.config.js in examples variables for dart-sass and running ../../node_modules/.bin/webpack
will result into an error.
ERROR in ./src/scss/style.scss
Module build failed (from /home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from /home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/sass-loader/lib/loader.js):
$sprite: sprite-str-replace($sprite, '___#{$key}___', sprite-svg-uri(quote($value)));
^
$string: #f00 is not a string.
╷
65 │ $sprite: sprite-str-replace($sprite, '___#{$key}___', sprite-svg-uri(quote($value)));
│ ^^^^^^^^^^^^^
╵
src/scss/_sprites.scss 65:82 sprite()
stdin 4:5 root stylesheet
in /home/cstornowski/Downloads/svg-spritemap-webpack-plugin/examples/variables/src/scss/_sprites.scss (line 65, column 82)
at runLoaders (/home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/webpack/lib/NormalModule.js:301:20)
at /home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/loader-runner/lib/LoaderRunner.js:364:11
at /home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/loader-runner/lib/LoaderRunner.js:230:18
at context.callback (/home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/loader-runner/lib/LoaderRunner.js:111:13)
at render (/home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/sass-loader/lib/loader.js:52:13)
at Function.$2 (/home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/sass/sass.dart.js:24106:48)
at w4.$0 (/home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/sass/sass.dart.js:15152:8)
at Object.Gd (/home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/sass/sass.dart.js:469:30)
at Object.hp (/home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/sass/sass.dart.js:2216:29)
at Ha (/home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/sass/sass.dart.js:3044:27)
at /home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/sass/sass.dart.js:3033:42
@ ./src/index.js 1:0-28
Child mini-css-extract-plugin ../../node_modules/css-loader/dist/cjs.js!../../node_modules/sass-loader/lib/loader.js??ref--4-2!src/scss/style.scss:
Entrypoint mini-css-extract-plugin = *
[0] /home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/css-loader/dist/cjs.js!/home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/sass-loader/lib/loader.js??ref--4-2!./src/scss/style.scss 803 bytes {0} [built] [failed] [1 error]
ERROR in ./src/scss/style.scss (/home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/css-loader/dist/cjs.js!/home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/sass-loader/lib/loader.js??ref--4-2!./src/scss/style.scss)
Module build failed (from /home/cstornowski/Downloads/svg-spritemap-webpack-plugin/node_modules/sass-loader/lib/loader.js):
$sprite: sprite-str-replace($sprite, '___#{$key}___', sprite-svg-uri(quote($value)));
^
$string: #f00 is not a string.
╷
65 │ $sprite: sprite-str-replace($sprite, '___#{$key}___', sprite-svg-uri(quote($value)));
│ ^^^^^^^^^^^^^
╵
src/scss/_sprites.scss 65:82 sprite()
stdin 4:5 root stylesheet
in /home/cstornowski/Downloads/svg-spritemap-webpack-plugin/examples/variables/src/scss/_sprites.scss (line 65, column 82)
diff --git a/examples/variables/webpack.config.js b/examples/variables/webpack.config.js
index 9f6c651..7ef8832 100644
--- a/examples/variables/webpack.config.js
+++ b/examples/variables/webpack.config.js
@@ -1,6 +1,8 @@
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const SVGSpritemapPlugin = require('../../lib');
+const sass = require('sass');
+const fibers = require('fibers');
module.exports = {
module: {
@@ -8,8 +10,11 @@ module.exports = {
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
- 'css-loader',
- 'sass-loader'
+ {loader:'css-loader'},
+ {loader: 'sass-loader', options: {
+ implementation: sass,
+ fiber: fibers
+ }}
]
}]
},
npm install mini-css-extract-plugin css-loader style-loader sass-loader sass fibers less-loader less html-webpack-plugin webpack-dev-server --no-save
Hi,
Webpack 4.20
with Symfony encore
It's working very well with the 2.7.1 version
With the 3.0.0 version my manifest json look like this
"build/svg/icons.59cf10a6f7abb6fad7fd.svg": "/build/svg/icons.59cf10a6f7abb6fad7fd.svg"
any ideas why ?
my config :
new SvgStorePlugin("svg/**/*.svg", {
output: {
chunk: { name: "svg/icons" },
filename: "svg/icons.[hash].svg",
svgo: true
},
sprite: {
prefix: "icon-",
}
})
Thanks !
At the end of webpack compilation, I receive EOENT because the created 'spritemap.js' is no longer there. This may be because of other reporting tools in the stack.
A parameter in the options to not delete the .js file would be helpful
Hey, I'm wondering if there is any specific reason output file is locked to output.path
?
I'm working on the setup where I need to compile svg into /public
path, which is outside output.path
folder. Would you consider pull request for it? Or maybe you can recommend some solutions with "as is" code? All I could come up with - a package scripts command to build svg by npm run svg
, but I'd like it to be automated.
I have a particular SVG that I know should be optimized by SVGO (because I can manually run it through SVGO and see a path deeply nested within transform groups get optimized into a single top level path). Here's the plugin config I'm using:
new SVGSpritemapPlugin(
'./assets/svg/*.svg', {
output: {
filename: 'lib/svg/dlssprite-new.svg',
svgo: true
},
sprite: {
prefix: false
}
}
);
I've also tried various forms for svgo options such as:
svgo: {
plugins: [
{ removeTitle: true },
{ removeStyleElement: true }
]
}
and
svgo: {
plugins: [{
removeTitle: true,
removeStyleElement: true
}]
}
Input SVG:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="LTL-R4---Advanced" stroke="none" fill-rule="evenodd">
<g id="P1-01A-Advanced---Item-Template-Copy" transform="translate(-635.000000, -1554.000000)">
<g id="step-3" transform="translate(45.000000, 1181.000000)">
<g id="additional-services" transform="translate(11.000000, 335.000000)">
<g id="blind-ship" transform="translate(540.000000, 38.000000)">
<g id="Group" transform="translate(39.000000, 0.000000)">
<g id="Group-3">
<path d="M20.6310006,3.66328621 C20.6469053,3.67730158 20.6624712,3.69190844 20.6776695,3.70710678 C20.7048296,3.73426688 20.7301008,3.7626006 20.753483,3.7919447 C22.7668686,5.93824539 24,8.82522294 24,12 C24,18.627 18.627,24 12,24 C8.82522294,24 5.93824539,22.7668686 3.7919447,20.753483 C3.7626006,20.7301008 3.73426688,20.7048296 3.70710678,20.6776695 C3.69190844,20.6624712 3.67730158,20.6469053 3.66328621,20.6310006 C1.40461436,18.4488601 0,15.3883409 0,12 C0,5.373 5.373,0 12,0 C15.3883409,0 18.4488601,1.40461436 20.6310006,3.66328621 Z M18.8888265,4.08173622 C17.0437196,2.4744434 14.6335794,1.5 12,1.5 C6.21,1.5 1.5,6.21 1.5,12 C1.5,14.6335794 2.4744434,17.0437196 4.08173622,18.8888265 L8.34667478,14.623888 C7.41722206,13.9424849 6.67856863,13.1536556 6.228,12.62 C5.924,12.26 5.924,11.74 6.228,11.38 C7.177,10.256 9.404,8 12,8 C12.8408985,8 13.6430797,8.23671013 14.3756153,8.59494744 L18.8888265,4.08173622 Z M20.2665307,5.53245918 L16.0869812,9.71200864 C16.8128969,10.304652 17.3934044,10.9317006 17.771,11.379 C18.076,11.74 18.076,12.26 17.771,12.621 C16.823,13.744 14.596,16 12,16 C11.3596479,16 10.7417478,15.8627326 10.1599426,15.6390472 L5.53245918,20.2665307 C7.31632701,21.6652271 9.56245706,22.5 12,22.5 C17.79,22.5 22.5,17.79 22.5,12 C22.5,9.56245706 21.6652271,7.31632701 20.2665307,5.53245918 Z M11.8080832,13.9909067 C11.8712478,13.9969229 11.9352664,14 12,14 C13.104,14 14,13.105 14,12 C14,11.9352594 13.9969243,11.8712396 13.9909114,11.8080785 L11.8080832,13.9909067 Z M10.1676827,12.8028801 L12.8028534,10.1677094 C12.5570772,10.0598518 12.2854934,10 12,10 C10.896,10 10,10.895 10,12 C10,12.2855972 10.0598537,12.5571661 10.1676827,12.8028801 Z" id="Combined-Shape"></path>
</g>
</g>
</g>
</g>
</g>
</g>
</g>
</svg>
Expected output (generated by manually running svgo from the command line using default options):
<svg viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg">
<path d="M20.631 3.663a1.015 1.015 0 0 1 .122.129A11.958 11.958 0 0 1 24 12c0 6.627-5.373 12-12 12a11.958 11.958 0 0 1-8.208-3.247 1.01 1.01 0 0 1-.129-.122A11.965 11.965 0 0 1 0 12C0 5.373 5.373 0 12 0c3.388 0 6.449 1.405 8.631 3.663zm-1.742.419A10.456 10.456 0 0 0 12 1.5C6.21 1.5 1.5 6.21 1.5 12c0 2.634.974 5.044 2.582 6.889l4.265-4.265a12.657 12.657 0 0 1-2.119-2.004.957.957 0 0 1 0-1.24C7.177 10.256 9.404 8 12 8c.84 0 1.643.237 2.376.595l4.513-4.513zm1.378 1.45l-4.18 4.18c.726.593 1.306 1.22 1.684 1.667a.957.957 0 0 1 0 1.242C16.823 13.744 14.596 16 12 16c-.64 0-1.258-.137-1.84-.361l-4.628 4.628A10.449 10.449 0 0 0 12 22.5c5.79 0 10.5-4.71 10.5-10.5 0-2.438-.835-4.684-2.233-6.468zm-8.459 8.459a2 2 0 0 0 2.183-2.183l-2.183 2.183zm-1.64-1.188l2.635-2.635a2 2 0 0 0-2.635 2.635z" fill-rule="evenodd"/>
</svg>
The symbols generated by the plugin has a viewbox
with wrong parameters, see attached file. The top / left values are always 0
When using the plugin with a custom styles
parameter, e.g. styles: '~icons.scss'
, I would expect to be able to call the map mixin like this:
@import '~svg-spritemap-webpack-plugin/icons';
background-image: url(map-get($icons, 'logo'));
Currently, that gives me an error, Undefined variable: "$icons"
. Therefore it seems, that the generated map always get's stored in the variable $sprites
So this is working
@import '~svg-spritemap-webpack-plugin/icons';
background-image: url(map-get($sprites, 'logo'));
Is that intended or should the map variable be available under the same same as specified in the styles
parameter?
When also generating a CSS file [contenthash] & [hash] doesn't seem to work!
...
styles : {
filename : 'my-css-[hash].css'
}
...
i have tried it with both 3.0.0-rc.2 and 2.7.1 and they both generate the file but do not add [contenthash] & [hash]...for example they just output a file like this -> my-css-[hash].css (with the literal [hash] text)
[contenthash] & [hash] works OK when using it for the SVG option
...
output : {
filename : 'spritemap-[contenthash].svg'
}
...
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.