svg-url-loader
A webpack loader which loads SVG file as utf-8 encoded DataUrl string.
Existing url-loader
always does Base64 encoding for data-uri. As SVG content is a human-readable xml string, using base64 encoding is not mandatory. Instead, one may only escape unsafe characters and replace "
with '
as described in this article.
There are some benefits for choosing utf-8 encoding over base64.
- Resulting string is shorter (can be ~2 times shorter for 2K-sized icons);
- Resulting string will be compressed better when using gzip compression;
- Browser parses utf-8 encoded string faster than its base64 equivalent.
Supported parameters
Parameters can be passed both in a url or from webpack config file. See Loaders section in webpack documentation for more details.
The loader supports the following parameters:
noquotes
Passing this parameter (or setting to true
) tells to loader not to include resulting string in quotes. This can be useful if one wants to use data-url for SVG image as a value for JavaScript variable.
limit
If given will tell the loader not to encode the source file if its content is greater than this limit.
Defaults to no limit.
If the file is greater than the limit the file-loader
is used and all query parameters are passed to it.
require("svg-url?limit=1024!./file.svg");
// => DataUrl if "file.png" is smaller that 1kb
require("svg-url?prefix=img/!./file.svg");
// => Parameters for the file-loader are valid too
// They are passed to the file-loader if used.
Usage
In JS:
require("svg-url!./file.svg");
// => DataUrl for file.svg, enclosed in quotes
require("svg-url?noquotes!./file.svg");
// => DataUrl for file.svg, without quotes
In CSS (with webpack.config.js below):
.icon {
background: url('../images/file.svg');
}
module.exports = {
//...
module: {
rules: [
{
test: /\.svg/,
use: {
loader: 'svg-url-loader',
options: {}
}
}
]
},
//...
};