I'm using the svg
loader to import SVG icons in my React file.
webpack.config.js
:
{ test: /\.svg(\?.*)?$/, loader: 'svg' }
component.js
:
import Icon from './icon.svg'
render () {
return <svg {...Icon.attributes} dangerouslySetInnerHTML={{ __html: Icon.content }} />
}
So far I have no issues. I also want to use SVG images in my CSS. If I do this:
.class {
background-image: url('./icon.svg');
}
My final result looks like this:
I would like to use the url
loader for my CSS file. I tried this:
.class {
url('url!./icon.svg?name=[path][name].[ext]&limit=1&mimetype=image/svg+xml');
}
In my CSS I get:
This looks like what I want but the image is not displayed and if I open the url in a separate tab I get this:
Which leads me to think that the svg loader is still running.
Is there a way to specify a different loader based on from which file I'm importing?
Webpack enables use of loaders to preprocess files. This allows you to bundle any static resource way beyond JavaScript. You can easily write your own loaders using Node.
In the following code block, css-loader and style-loader are used together. Similar to babel-loader , we can load CSS files to style our pages like so: module: { rules: [ { test: /\\. js$/, loader: "babel-loader", exclude: "/node_modules/", }, // CSS rules { test: /\\.
Webpack goes through all the import ed and require d files in your project, and for all those files which have a . svg extension, it uses as an input to the webpack file loader. For each of these files, the file loader emits the file in the output directory and resolves the correct URL to be referenced.
Add issuer see: webpack.js.org/configuration/module/#rule-issuer
An example:
{
test: /\.svg(\?.*)?$/,
issuer: /\.js$/,
loader: 'svg-inline-loader',
},
{
test: /\.svg/,
issuer: /\.scss$/,
use: {
loader: 'svg-url-loader',
options: {},
},
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With