Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use different loader in Webpack depending on from where I'm importing

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:

background-image: url([object Object]);

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:

background-image: url(data:image/svg+xml;base64,bW9...

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:

module.exports = {"attributes":{"xmlns":"http://w...

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?

like image 617
Giorgio Polvara - Gpx Avatar asked Mar 29 '16 10:03

Giorgio Polvara - Gpx


People also ask

When using webpack Why would you need to use a loader when using webpack Why would you need to use a loader?

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.

How do I use CSS modules with Webpacks?

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: /\\.

How does webpack file loader work?

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.


1 Answers

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: {},
  },
},
like image 62
alexrogers Avatar answered Nov 16 '22 01:11

alexrogers