babel-plugin-inline-react-svg
babel-plugin-inline-react-svg copied to clipboard
Can't get this plugin to work / Don't understand how to use it
What we had before:
-
react-svg-loader (400KB(!) minified + gzipped) webpack.config.js:
test: /\.svg$/, use: [ 'babel-loader', { loader: 'react-svg-loader', options: { svgo: { plugins: [ { removeTitle: false }, ], }, }, }, ],
In a .jsx file we import svg's like:
import Logo from 'assets/logo.svg'; // get's it from root even though component is in subfolder
import Logo from '../assets/logo.svg'; // I tried this as well with this module (correct relative)
What I did to replace react-svg-loader with babel-plugin-inline-react-svg:
webpack.config.js:
test: /\.svg$/,
use: [
'babel-loader',
],
.babelrc
- "@babel/plugin-proposal-function-bind"
+ "@babel/plugin-proposal-function-bind",
+ [
+ "inline-react-svg",
+ {
+ "svgo": {
+ "plugins": [
+ {
+ "removeAttrs": { "attrs": "(data-name)" }
+ },
+ {
+ "cleanupIDs": true
+ },
+ { "removeTitle": false }
+ ]
+ }
+ }
+ ]
The result?: lots of these...:
Module build failed: Error: Cannot find module 'assets/logo.svg'
assets there - as a non-relative path - is presumably a webpack-only alias.
My suggestion is to not use webpack aliases at all - either to use the relative paths, or, to use a babel transform for your aliases, so that everything can use it.
If the relative one didn't work, and the file is actually loaded there, then that's something that we should explore.
Also saying having issues with this.
I'm working within a Rails project and had resolved_paths set to my asset directory. I saw you mention not to use this so I removed it and tried referring to my SVG files relatively but get a webpack warning saying it cannot find the module.
I worked out why this wasn't working my specific case... basically don't use the rails asset pipeline to load your SVGs, I had to move them into the same directory as my React app and use the relative URL.
I tried to use relative url also as described above
import Logo from '../assets/logo.svg'; // I tried this as well with this module (corre
it also lives inside the same folder as the React app but I still got Error: Cannot find module 'assets/logo.svg'
@OZZlE Are you using any other loaders that are targeting SVG files? I had to also add an ignorePattern to my config to make sure images in the Rails asset pipeline were ignored.
@andrecalvo nope no other loaders targeting .svg in webpack.config.js
Ah or I kept babel-loader' for it because this approach seems to rely on babel? maybe that was wrong.. will have to re-test this in the next sprint(s) when I have a ticket for this again
yes, this approach relies on babel, and you’d want to avoid using the rails asset pipeline for svgs when using it.