Giter VIP home page Giter VIP logo

gatsby-plugin-react-svg's Introduction

gatsby-plugin-react-svg npm version

Adds svg-react-loader to gatsby webpack config.

Note: the plugin can remove SVGs from the built-in url-loader config in case invalid configuration.

Install

npm install --save gatsby-plugin-react-svg

How to use

// In your gatsby-config.js

plugins: [
  {
    resolve: "gatsby-plugin-react-svg",
    options: {
      rule: {
        include: /assets/ // See below to configure properly
      }
    }
  }
];

Configuration

The rule plugin option can be used to pass rule options. If either include or exclude options are present, svg-react-loader will use them and url-loader will be re-enabled with the inverse.

The following configuration uses svg-react-loader to process SVGs from a path matching /assets/, and url-loader to process SVGs from everywhere else.

{
  resolve: 'gatsby-plugin-react-svg',
  options: {
    rule: {
      include: /assets/
    }
  }
}

From now on you can import SVGs and use them as Components:

import Icon from "./path/assets/icon.svg";

// ...

<Icon />;

Another common configuration:

  • name SVGs used in React components like something.inline.svg and process them with svg-react-loader
  • name other SVGs (e.g. used in css/scss) something.svg and process them with the default url-loader
{
  resolve: 'gatsby-plugin-react-svg',
  options: {
    rule: {
      include: /\.inline\.svg$/
    }
  }
}

In React components:

import Something from "./path/something.inline.svg";

// ...

<Something />;

In styles file:

.header-background {
  background-image: url(./path/something.svg);
}

Using with typescript

To use SVGs with Typescript, create a custom type definition like this:

declare module "*.svg" {
  const content: any;
  export default content;
}

Make sure the file is contained in your tsconfig.json include.

SVG-React-Loader options

Any of the svg-react-loader query parameters can be passed down via the webpack config by including an options prop within the rule prop.

// In your gatsby-config.js

plugins: [
  {
    resolve: "gatsby-plugin-react-svg",
      options: {
        rule: {
          include: /\.inline\.svg$/,
          options: {
            tag: "symbol",
            name: "MyIcon",
            props: {
              className: "my-class",
              title: "example"
            },
            filters: [value => console.log(value)]
          }
        }
      }
  }
];

They can also be defined at the import level:

  import Fork from "-!svg-react-loader?props[]=className:w-4 h-4!../components/Icons/Fork.inline.svg";

Removing svg props (filters)

Unwanted SVG props can be removed with filters. Since filters are quite complex this plugin adds a simple key omitKeys to allow end users to quickly remove props that are problematic from their svg files.

{
  resolve: `gatsby-plugin-react-svg`,
  options: {
    rule: {
      include: /images\/.*\.svg/,
      omitKeys: ['xmlnsDc', 'xmlnsCc', 'xmlnsRdf', 'xmlnsSvg', 'xmlnsSodipodi', 'xmlnsInkscape']
      ///OR
      filters: [(value) => { console.log(value); }]
    }
  }
},

Troubleshooting

I get "InvalidCharacterError" overlay in my browser during development

Example of this error:

InvalidCharacterError: Failed to execute 'createElement' on 'Document':
The tag name provided ('data:image/svg+xml; ...

It's likely that you use SVG in your React component, that is processed by url-loader instead of svg-react-loader due to incorrect configuration.

I get endless spinner (with an infinite loop in the background) in my browser during development

It's likely that some of your SVGs used in css/sass files are processed by svg-react-loader instead of url-loader due to incorrect configuration.

I get error "Module parse failed" in console

Example of this error:

ERROR in ./src/images/some-image.png 1:0
Module parse failed: Unexpected character '' (1:0)

In case you see such error, it's likely that you configured exclude/include rule options incorrectly. Please check configuration section above.

gatsby-plugin-react-svg's People

Contributors

alampros avatar artamonovtech avatar egorzekov avatar gregorskii avatar jackw avatar jacobmischka avatar kornil avatar lekoarts avatar schmidt-aaron avatar simonvomeyser avatar stefanpl avatar tsamantanis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

gatsby-plugin-react-svg's Issues

receiving Error: Invalid character entity when importing an svg file as Component

In my gatsby-config.js I have

{
      resolve: "gatsby-plugin-react-svg",
      options: {
        rule: {
          include: /svg/,
        },
      },
    },

then in my LandingPage.js component I have

// other imports
import Hacker from "../svg/hacker.svg"
const LandingPage = () => {
  //...
  return (
             <>
                 //...
                 <Hacker />
                //...
             </>
  )
}

when I run pnpm dev (script for gatsby develop -H 0.0.0.0 -o) I get

> gatsby develop -H 0.0.0.0 -o

warn Plugin gatsby-plugin-intl is not compatible with your gatsby version 4.4.0 - It requires gatsby@^2.0.0
warn Plugin gatsby-plugin-netlify is not compatible with your gatsby version 4.4.0 - It requires gatsby@^3.0.0
warn Plugin gatsby-plugin-intl is not compatible with your gatsby version 4.4.0 - It requires gatsby@^2.0.0
warn Plugin gatsby-plugin-netlify is not compatible with your gatsby version 4.4.0 - It requires gatsby@^3.0.0
success open and validate gatsby-configs, load plugins - 2.130s
success onPreInit - 0.006s
success initialize cache - 0.163s
success copy gatsby files - 0.350s
success Compiling Gatsby Functions - 0.453s
success onPreBootstrap - 0.482s
success createSchemaCustomization - 0.023s
success Checking for changed pages - 0.002s
success source and transform nodes - 0.284s
success building schema - 0.699s
success createPages - 0.115s
success createPagesStatefully - 0.201s
info Total nodes: 108, SitePage nodes: 21 (use --verbose for breakdown)
success Checking for changed pages - 0.002s
success write out redirect data - 0.003s
success Build manifest and related icons - 0.113s
success onPostBootstrap - 0.121s
info bootstrap finished - 8.898s
success onPreExtractQueries - 0.002s
success extract queries from components - 2.653s
success write out requires - 0.141s
success run static queries - 0.024s - 2/2 84.38/s
success run page queries - 0.272s - 3/3 11.03/s
success Running gatsby-plugin-sharp.IMAGE_PROCESSING jobs - 0.696s - 10/10 14.37/s

 ERROR 

Module build failed (from ./node_modules/.pnpm/svg-react-loader@0.4.6/node_modules/svg-react-loader/lib/loader.js):
Error: Invalid character entity
Line: 12
Column: 52
Char: ;
    at error (E:\TRABAJO\web\1. Proyectos\massick-portfolio\node_modules\.pnpm\sax@1.2.4\node_modules\sax\lib\sax.js:651:10)
    at strictFail (E:\TRABAJO\web\1. Proyectos\massick-portfolio\node_modules\.pnpm\sax@1.2.4\node_modules\sax\lib\sax.js:677:7)
    at parseEntity (E:\TRABAJO\web\1. Proyectos\massick-portfolio\node_modules\.pnpm\sax@1.2.4\node_modules\sax\lib\sax.js:937:7)
    at SAXParser.write (E:\TRABAJO\web\1. Proyectos\massick-portfolio\node_modules\.pnpm\sax@1.2.4\node_modules\sax\lib\sax.js:1485:31)
    at Parser.exports.Parser.Parser.parseString (E:\TRABAJO\web\1.
Proyectos\massick-portfolio\node_modules\.pnpm\xml2js@0.4.17\node_modules\xml2js\lib\xml2js.js:508:31)
    at Parser.parseString (E:\TRABAJO\web\1. Proyectos\massick-portfolio\node_modules\.pnpm\xml2js@0.4.17\node_modules\xml2js\lib\xml2js.js:7:59)      
    at AnonymousObservable.__subscribe (E:\TRABAJO\web\1.
Proyectos\massick-portfolio\node_modules\.pnpm\svg-react-loader@0.4.6\node_modules\svg-react-loader\lib\xml\parse.js:16:16)
    at AnonymousObservable.tryCatcher (E:\TRABAJO\web\1. Proyectos\massick-portfolio\node_modules\.pnpm\rx@4.1.0\node_modules\rx\dist\rx.js:63:31)     
    at setDisposable (E:\TRABAJO\web\1. Proyectos\massick-portfolio\node_modules\.pnpm\rx@4.1.0\node_modules\rx\dist\rx.js:5845:44)
    at AnonymousObservable.Rx.AnonymousObservable.AnonymousObservable._subscribe (E:\TRABAJO\web\1.
Proyectos\massick-portfolio\node_modules\.pnpm\rx@4.1.0\node_modules\rx\dist\rx.js:5862:9)
    at AnonymousObservable.Rx.Observable.observableProto.subscribe.observableProto.forEach (E:\TRABAJO\web\1.
Proyectos\massick-portfolio\node_modules\.pnpm\rx@4.1.0\node_modules\rx\dist\rx.js:2034:19)
    at CatchObserver.error (E:\TRABAJO\web\1. Proyectos\massick-portfolio\node_modules\.pnpm\rx@4.1.0\node_modules\rx\dist\rx.js:3255:30)
    at CatchObserver.Rx.internals.AbstractObserver.AbstractObserver.onError (E:\TRABAJO\web\1.
Proyectos\massick-portfolio\node_modules\.pnpm\rx@4.1.0\node_modules\rx\dist\rx.js:1772:14)
    at CatchObserver.tryCatcher (E:\TRABAJO\web\1. Proyectos\massick-portfolio\node_modules\.pnpm\rx@4.1.0\node_modules\rx\dist\rx.js:63:31)
    at AutoDetachObserverPrototype.error (E:\TRABAJO\web\1. Proyectos\massick-portfolio\node_modules\.pnpm\rx@4.1.0\node_modules\rx\dist\rx.js:5891:52)    at AutoDetachObserver.Rx.internals.AbstractObserver.AbstractObserver.onError (E:\TRABAJO\web\1.
Proyectos\massick-portfolio\node_modules\.pnpm\rx@4.1.0\node_modules\rx\dist\rx.js:1772:14)



  ModuleBuildError: Module build failed (from ./node_modules/.pnpm/svg-react-loader@0.4.6/node_modules/svg-react-loader/lib/loader.js):
  Error: Invalid character entity
  Line: 12
  Column: 52
  Char: ;

  - sax.js:651 error
    [massick-portfolio]/[sax@1.2.4]/[sax]/lib/sax.js:651:10

  - sax.js:677 strictFail
    [massick-portfolio]/[sax@1.2.4]/[sax]/lib/sax.js:677:7

  - sax.js:937 parseEntity
    [massick-portfolio]/[sax@1.2.4]/[sax]/lib/sax.js:937:7

  - sax.js:1485 SAXParser.write
    [massick-portfolio]/[sax@1.2.4]/[sax]/lib/sax.js:1485:31

  - xml2js.js:508 Parser.exports.Parser.Parser.parseString
    [massick-portfolio]/[xml2js@0.4.17]/[xml2js]/lib/xml2js.js:508:31

  - xml2js.js:7 Parser.parseString
    [massick-portfolio]/[xml2js@0.4.17]/[xml2js]/lib/xml2js.js:7:59

  - parse.js:16 AnonymousObservable.__subscribe
    [massick-portfolio]/[svg-react-loader@0.4.6]/[svg-react-loader]/lib/xml/parse.js:16:16

  - rx.js:63 AnonymousObservable.tryCatcher
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:63:31

  - rx.js:5845 setDisposable
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:5845:44

  - rx.js:5862 AnonymousObservable.Rx.AnonymousObservable.AnonymousObservable._subscribe
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:5862:9

  - rx.js:2034 AnonymousObservable.Rx.Observable.observableProto.subscribe.observableProto.forEach
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:2034:19

  - rx.js:3255 CatchObserver.error
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:3255:30

  - rx.js:1772 CatchObserver.Rx.internals.AbstractObserver.AbstractObserver.onError
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:1772:14

  - rx.js:63 CatchObserver.tryCatcher
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:63:31

  - rx.js:5891 AutoDetachObserverPrototype.error
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:5891:52

  - rx.js:1772 AutoDetachObserver.Rx.internals.AbstractObserver.AbstractObserver.onError
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:1772:14

  - NormalModule.js:751 processResult
    [massick-portfolio]/[webpack@5.65.0]/[webpack]/lib/NormalModule.js:751:19

  - NormalModule.js:853 
    [massick-portfolio]/[webpack@5.65.0]/[webpack]/lib/NormalModule.js:853:5

  - LoaderRunner.js:399 
    [massick-portfolio]/[loader-runner@4.2.0]/[loader-runner]/lib/LoaderRunner.js:399:11

  - LoaderRunner.js:251 
    [massick-portfolio]/[loader-runner@4.2.0]/[loader-runner]/lib/LoaderRunner.js:251:18

  - LoaderRunner.js:124 AnonymousObserver.context.callback [as _onError]
    [massick-portfolio]/[loader-runner@4.2.0]/[loader-runner]/lib/LoaderRunner.js:124:13

  - rx.js:1836 AnonymousObserver.Rx.AnonymousObserver.AnonymousObserver.error
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:1836:12

  - rx.js:1772 AnonymousObserver.Rx.internals.AbstractObserver.AbstractObserver.onError
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:1772:14

  - rx.js:63 AnonymousObserver.tryCatcher
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:63:31

  - rx.js:5891 AutoDetachObserverPrototype.error
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:5891:52

  - rx.js:1772 AutoDetachObserver.Rx.internals.AbstractObserver.AbstractObserver.onError
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:1772:14

  - rx.js:5413 InnerObserver.error
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:5413:14

  - rx.js:1772 InnerObserver.Rx.internals.AbstractObserver.AbstractObserver.onError
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:1772:14

  - rx.js:63 InnerObserver.tryCatcher
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:63:31

  - rx.js:5891 AutoDetachObserverPrototype.error
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:5891:52

  - rx.js:1772 AutoDetachObserver.Rx.internals.AbstractObserver.AbstractObserver.onError
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:1772:14

  - rx.js:63 AutoDetachObserver.tryCatcher
    [massick-portfolio]/[rx@4.1.0]/[rx]/dist/rx.js:63:31


not finished Building development bundle - 23.647s

 ELIFECYCLE  Command failed with exit code 1.

gatsby info:

System:
    OS: Windows 10 10.0.19042
    CPU: (4) x64 Intel(R) Core(TM) i3-6100 CPU @ 3.70GHz  
  Binaries:
    Node: 14.16.0 - C:\Program Files\nodejs\node.EXE      
    npm: 6.14.11 - C:\Program Files\nodejs\npm.CMD        
  Browsers:
    Edge: Spartan (44.19041.423.0), Chromium (94.0.992.50)
  npmPackages:
    gatsby: ^4.4.0 => 4.4.0
    gatsby-plugin-dark-mode: ^1.1.2 => 1.1.2
    gatsby-plugin-feed: ^4.4.0 => 4.4.0
    gatsby-plugin-gatsby-cloud: ^4.4.0 => 4.4.0
    gatsby-plugin-google-analytics: ^4.4.0 => 4.4.0
    gatsby-plugin-image: ^2.4.0 => 2.4.0
    gatsby-plugin-intl: ^0.3.3 => 0.3.3
    gatsby-plugin-manifest: ^4.4.0 => 4.4.0
    gatsby-plugin-netlify: ^3.14.0 => 3.14.0
    gatsby-plugin-offline: ^5.4.0 => 5.4.0
    gatsby-plugin-pnpm: ^1.2.9 => 1.2.9
    gatsby-plugin-postcss: ^5.4.0 => 5.4.0
    gatsby-plugin-react-helmet: ^5.4.0 => 5.4.0
    gatsby-plugin-react-svg: ^3.1.0 => 3.1.0
    gatsby-plugin-sharp: ^4.4.0 => 4.4.0
    gatsby-plugin-webpack-bundle-analyser-v2: ^1.1.26 => 1.1.26
    gatsby-remark-copy-linked-files: ^5.4.0 => 5.4.0
    gatsby-remark-images: ^6.4.0 => 6.4.0
    gatsby-remark-prismjs: ^6.4.0 => 6.4.0
    gatsby-remark-responsive-iframe: ^5.4.0 => 5.4.0
    gatsby-remark-smartypants: ^5.4.0 => 5.4.0
    gatsby-source-filesystem: ^4.4.0 => 4.4.0
    gatsby-transformer-remark: ^5.4.0 => 5.4.0
    gatsby-transformer-sharp: ^4.4.0 => 4.4.0
  npmGlobalPackages:
    gatsby-cli: 4.2.0

If you want to reproduce it, this is my repo. Run pnpm dev on it.

Unsupported in Gatsby v2

This plugin does not seem to be compatible with Gatsby v2.

The command gatsby develop works fine

But upon a gatsby build

 
The plugin "[email protected]" is exporting a variable named "modifyWebpackConfig" which isn't an API. Perhaps you meant to export "onCreateWebpackConfig"?

The Gatsby v1 docs has modifyWebpackConfig as a gatsby-node API
Gatsby v1 node api docs
The Gatsby v2 docs have changed it to onCreateWebpackConfig
Gatsby v2 node api docs

Provide/fix instructions

I had to look in your package.json file to find the npm name for this plugin (@jacobmischka/gatsby-plugin-react-svg) in order to install it.

After installing it I added the configuration in your readme to my gatsby-config.js file (your readme does not currently instruct this).

That got me Error: Unable to find plugin "gatsby-plugin-react-svg".

The config should in fact have resolve: "@jacobmischka/gatsby-plugin-react-svg",.

Multiple same svg only render single svg

lets say i have one svg which has linearGradient with id, and i wanted to try render the same svg on multiple places within the same page. only the first one got render because the id is conflicting. is there a way to get a workaround on this, or can we modify the id on specific path?

svg example

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
    <defs>
        <linearGradient id="94h1ukeypa" x1="0%" x2="100%" y1="95.92%" y2="4.08%">
            <stop offset="0%" stop-color="#FF444F"/>
            <stop offset="100%" stop-color="#FF6444"/>
        </linearGradient>
    </defs>
    <g fill="none" fill-rule="evenodd">
        <path d="M0 0H18V18H0z" transform="translate(3 3)"/>
        <path fill="url(#94h1ukeypa)" fill-rule="nonzero" d="M9 0c1.243 0 2.25 1.175 2.25 2.625 0 .834-.334 1.578-.854 2.058.974.348 1.737 1.17 2.038 2.196.28-.563.718-1.02 1.25-1.306-.567-.408-.934-1.072-.934-1.823 0-1.243 1.007-2.25 2.25-2.25s2.25 1.007 2.25 2.25c0 .765-.381 1.44-.965 1.847.876.486 1.49 1.444 1.545 2.568l.167 2.716c.019.23-.055.46-.203.628-.147.17-.355.263-.564.259l-.594-.001-.42 4.875c-.03.318-.26.565-.547.603l-.08.005h-1.22c-.33.001-.604-.271-.629-.624l-.338-4.693h-.633c-.179 0-.35-.067-.488-.187l.028.02c-.068.025-.14.04-.215.04h-.84c-.043 0-.08.034-.084.076l-.465 4.617c-.033.426-.374.752-.78.751H8.726c-.412 0-.754-.334-.781-.756l-.366-4.416c-.005-.05-.043-.087-.086-.087h-.705c-.213 0-.418-.09-.567-.251-.148-.16-.229-.377-.222-.603l.12-3.264c0-1.299.703-2.427 1.733-2.99-.66-.457-1.103-1.297-1.103-2.258C6.75 1.175 7.757 0 9 0zM3 1.5c1.243 0 2.25 1.007 2.25 2.25 0 .759-.376 1.43-.951 1.838.926.502 1.56 1.52 1.56 2.682l.14 2.702c.01.223-.066.441-.212.603-.146.162-.349.254-.56.253h-.584l-.423 4.821c-.03.314-.262.559-.55.596l-.08.005H2.376c-.332.001-.608-.268-.633-.617l-.34-4.641H.76c-.177-.003-.348-.07-.483-.19l-.064-.064c-.143-.158-.22-.37-.213-.59L.1 8.29c0-1.188.645-2.217 1.586-2.718C1.118 5.167.75 4.501.75 3.75.75 2.507 1.757 1.5 3 1.5zm6.347 3.737c-1.393 0-2.523 1.18-2.523 2.65l-.12 3.276c0 .024.008.047.024.064.016.018.038.027.061.027h.709c.407.005.745.33.784.757l.366 4.427c.003.042.037.075.079.075h1.199c.04 0 .074-.032.078-.082l.465-4.629c.046-.419.386-.735.787-.732H12l.016-.474-.147-2.723c0-1.35-.971-2.464-2.223-2.618L9.48 5.24zm-6.481.76H2.83C1.696 6.077.8 7.074.8 8.304l-.098 2.87c0 .02.007.039.02.053.013.014.03.023.044.023h.701c.332-.001.608.268.633.617l.339 4.641h1.088l.423-4.812c.029-.312.256-.558.55-.602l.08-.007h.647c.02 0 .038-.008.051-.023.013-.015.02-.035.02-.053l-.142-2.72c0-1.27-.975-2.3-2.177-2.3l.126.005L3 6c-.045 0-.09-.001-.134-.004zM14.964 6c-1.155 0-2.107.971-2.168 2.204l-.078 2.311.031.568c.002.032.001.063-.002.095l.021.005h.698c.33-.001.603.271.628.623l.337 4.694h1.096l.42-4.866c.029-.316.255-.565.546-.61l.081-.006h.664c.017 0 .035-.008.047-.022.012-.014.018-.033.016-.059l-.168-2.727C17.073 6.97 16.12 6 14.964 6zm-5.589-.75c.207 0 .375.168.375.375v2.25c0 .207-.168.375-.375.375S9 8.082 9 7.875v-2.25c0-.207.168-.375.375-.375zM15 2.248c-.83 0-1.502.672-1.502 1.502S14.17 5.252 15 5.252l-.042-.002h.056c.823-.005 1.488-.675 1.488-1.5 0-.83-.672-1.502-1.502-1.502zm-12 0c-.83 0-1.502.672-1.502 1.502S2.17 5.252 3 5.252l-.036-.002h.055c.82-.007 1.483-.676 1.483-1.5 0-.83-.672-1.502-1.502-1.502zM9 .784c-.872 0-1.578.824-1.578 1.841S8.128 4.466 9 4.466c.872 0 1.578-.824 1.578-1.841S9.872.784 9 .784z" transform="translate(3 3)"/>
    </g>
</svg>

This plugin works fine in development mode - but on prod it behaves different.

Like the title said - in dev mode its completly fine.:

Works fine

But when I build gatsby and serve it it looks like that:

Works not

The Code:

import Facebook from "-!svg-react-loader?props[]=className:w-10 h-10!./../images/icons/icon-facebook-drawn.svg"

<Facebook/>

I think It has something to do with the fact that I import all the svg's and then I dont use all of them.
I will only use instagram, when the use inserted an instagramaccount in the backend.

So I guess gatsby-plugin-react-svg loads all svgs and wants to use them all - so it pushes the missing ones to the existing ones.

Can this be right?

No instructions on how to use Regex in the options.rule.include

I have a specific case where I have both SVGs and other formats in my /assets/ folder and so I'd like the plugin to only pick out the .svg files. But I can't find a way to do this with Regex as it keeps throwing errors when used inside gatsby-node.js

Since this is a very common scenario I'd appreciate if there's some documentation on this. And if we have a solution I'd be happy to add the docs.

query parameter `classIdPrefix: true` not working

While this query parameter offers in the svg-react-loader documentation to prefix class and id names with the filename (in case classIdPrefix: true) or with a declared combination of interpolations (such as [name]-[hash:8] being shown in the documentation), it appears that the latter functionality never went from a work-in-progress, and unmerged pull requests, to actual implementation. The first case, simply setting to true is working fine, judging from comments in that repo. In the case of this gatsby plugin I have not gotten this case to work.

Ultimately, I'm trying to solve the common problem of multiple svgs on a page interfering with each other.

loadash vulnerability

Expected Behavior

yarn audit shouldn't return any audit problems

Actual Behavior

yarn audit returns High vulnerability
More info
https://www.npmjs.com/advisories/1065

Possible Solution

Upgrade lodash

Steps to Reproduce

  1. yarn audit / npm audit

Context

Currently breaks CI as we rely on audits

Environment

  • Node Version: v10.14.1
  • Package Manager Version: 6.4.1
  • Operating System: 18.6.0 Darwin Kernel Version 18.6.0: Thu Apr 25 23:16:27 PDT 2019; root:xnu-4903.261.4~2/RELEASE_X86_64 x86_64
  • Package Version: 2.1.1

Module parse failed: Unexpected character '​'

Hi there,

I am facing some parsing issues with some quite simple SVGs, with the following warning;

warn Module parse failed: Unexpected character '​' (3:25)

Any idea what is going on?

Include and exclude are not working correctly in all cases

I see that whatever gets passed as include or exclude to svg-react-loader will be added to url-loader too, just other way around, include --> exclude, exclude --> include.

That is not correct in all cases. For instance, all my images are held in the same directory. If I put that directory as include, it will be excluded for url-loader. That can be fixed by passing regex and checking for .svg extension. But, that is pointless, because svg-react-loader has test option for that extension, and passing regex with the same extension would be redundant, but it is important for url-loader to work. This gets even worse if I need to exclude node_modules (for any reason) because they will be included for url-loader.

I would like to be able to override those options. For instance, I would like to be able to pass urlLoaderInclude and urlLoaderExclude options and override default behavior as it is now.

Cannot get gatsby-plugin-react-svg to work in background-image CSS

I've had no problem using gatsby-plugin-react-svg as inline SVG, but I spent a good while trying to get it to work as the background-img of a div. In a component, something like:
<div className={styles.example} />
And then in the style sheet:
.example { background-image: url(../../public/icons/dog.svg); }

When inspecting the element in the DOM, I see the correct classname, and in the stylesheet:
.header-module--example--LwtAV { background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+CjxzdmcgeG1sbnM9Imh0d…NmYmZkZmEiIGZpbGw9IiNmYmZkZmEiLz4KCQk8L2c+Cgk8L2c+CjwvZz48L2c+IDwvc3ZnPgo=);

Nothing shows up of course in the browser.

Oh also in my config:
{ resolve: 'gatsby-plugin-react-svg', options: { rule: { include: /\.inline\.svg$/, }, }, },

I deleted all my inline svg (after getting that working) just to ensure that that wasn't the problem. Now this is the only instance of svg in the project, for testing purposes. Perhaps I missed something, but this is the exact example given in the docs, as far as I can tell.

Error query.substr is not a function

Running Gatsby Cli 2.12.37
This plugin 3.0.0

If I add this to gatsby.config.js
{
resolve: 'gatsby-plugin-react-svg',
options: {
rule: {
include: /svg/ OR /assets/ or whatever
}
}
},

I get this error during a build

ERROR #98123 WEBPACK

Generating development JavaScript bundle failed

query.substr is not a function

File: src\assets\svg\example.svg

I get this only when I add this plugin to config otherwise build is successful.

Default plugin setup not working in Gatsby version 3: "maskType"

When loading the default setup in gatsby version 3 it produces the following error:

Warning: React does not recognize the maskType prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase masktype instead. If you accidentally passed it from a parent component, remove it from the DOM element.

// gatsby-config.js
    {
      resolve: "gatsby-plugin-react-svg",
      options: {
        rule: {
          // include: /svg/,
          include: /\.inline\.svg$/,
        },
      },
    },
// index.js
import Logo from "../svg/logo.inline.svg"

const IndexPage = () => <Logo />

export default IndexPage

image

SVGO Support

Would it be possible to add an option to pass SVGO config and cleanup the SVG's according to those rules?

I've used react-svg-loader and it's worked great for an icon system.

I noticed also that gatsby-plugin-svgr also includes this as an option.

Dynamic imports

Is there a way to use dynamic imports? I'm trying to achieve something like this:

Icon.js component
<Container src={require(`static/icons/${icon}.svg`)} raw />

In use
<Icon icon="twitter" />

The idea is to call a single Icon component and just reference the icon names as opposed to importing individual assets

Thanks!

Attributes are stripped off of the svg element

Some attributes are critical for getting the svg to display properly, eg. preserveAspectRatio. All of the attributes are being stripped off of the <svg>. Consequently, I cant get my SVGs to display properly. I set up a demo here:

https://github.com/jeffmagill/gatsby-svg-issue

Reproduction steps are:

  • Create boilerplate gatsby site gatsby new .
  • Add gatsby-plugin-react-svg to package.json and gatsby-config.js
  • Add svg with preserveAspectRatio to /src/images
  • Import and add SVG component into index.js

You can see the attributes in the svg are present yet the HTML in the production build for index.js that the <svg> element doesnt have any attributes.

Unable to load SVG's from custom folder

I keep my svgs in src/images/svgs directory. Then I try to load them in component in such way:
import Icon from "../../images/svgs/icon.svg"

In gatsby-config.js i have following config:

        rule: {
          include: /images\/svgs/
        }

I was trying to do it also like this: /images(\/|\\)svgs/ and include: path.resolve(__dirname, 'src/images/svgs')

The last way doesn't even throw an error, it just blocks the browser and I have to close it and re open browser.

If I'm able to get error i have this one:
InvalidCharacterError: Failed to execute 'createElement' on 'Document':
The tag name provided ('data:image/svg+xml;

Which means that my configuration is wrong, how?

How to make this plugin working?

Typescript Error

Hi, thanks a lot for this plugin! I'm trying to use it with Typescript and have set up a custom typescript definition as described in the readme but I'm still getting hit with the error:

import Example from "../images/example.svg"

Cannot find module '../images/example.svg' or its corresponding type declarations.ts(2307)

My config files are:

// gatsby-config.ts

...
    {
      resolve: "gatsby-plugin-react-svg",
      options: {
        rule: {
          include: /images\/.*\.svg/,
        },
      },
    },
...
// declarations.d.ts

declare module "*.svg" {
  const content: any
  export default content
}
// tsconfig.json

{
  "$schema": "https://json.schemastore.org/tsconfig",
  "display": "Node 16",

  "compilerOptions": {
    "lib": ["es2021", "DOM"],
    "module": "commonjs",
    "target": "es2021",
    "jsx": "react",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["./src/declarations.d.ts"]
}

I've checked the image is at the specified path and the SVG does load to the page successfully. Do you have any idea what might be causing this? Thanks very much for any help - I realise this isn't anything wrong with the plugin itself.

Unable to resolve svg path in deploy(Netlify) but works in localhost

5:48:09 PM: failed Building production JavaScript and CSS bundles - 21.814s
5:48:09 PM: error Generating JavaScript bundles failed
5:48:09 PM: Can't resolve '../icons/coderapper.svg' in '/opt/build/repo/src/pages'
5:48:09 PM: If you're trying to use a package make sure that '../icons/coderapper.svg' is installed. If you're trying to use a local file make sure that the path is correct.
5:48:09 PM: error Generating JavaScript bundles failed
5:48:09 PM: Can't resolve '../icons/tarkalabs.svg' in '/opt/build/repo/src/pages'
5:48:09 PM: If you're trying to use a package make sure that '../icons/tarkalabs.svg' is installed. If you're trying to use a local file make sure that the path is correct.
5:48:09 PM: error Generating JavaScript bundles failed
5:48:09 PM: Can't resolve '../icons/railsfactory.svg' in '/opt/build/repo/src/pages'
5:48:09 PM: If you're trying to use a package make sure that '../icons/railsfactory.svg' is installed. If you're trying to use a local file make sure that the path is correct.
5:48:09 PM: error Generating JavaScript bundles failed
5:48:09 PM: Can't resolve '../icons/eam360.svg' in '/opt/build/repo/src/pages'
5:48:09 PM: If you're trying to use a package make sure that '../icons/eam360.svg' is installed. If you're trying to use a local file make sure that the path is correct.
5:48:10 PM: ​
5:48:10 PM: ────────────────────────────────────────────────────────────────
5:48:10 PM: "build.command" failed
5:48:10 PM: ────────────────────────────────────────────────────────────────
5:48:10 PM: ​
5:48:10 PM: Error message
5:48:10 PM: Command failed with exit code 1: npm run build
5:48:10 PM: ​
5:48:10 PM: Error location
5:48:10 PM: In Build command from Netlify app:
5:48:10 PM: npm run build
5:48:10 PM: ​
5:48:10 PM: Resolved config
5:48:10 PM: build:
5:48:10 PM: command: npm run build
5:48:10 PM: commandOrigin: ui
5:48:10 PM: publish: /opt/build/repo/public
5:48:10 PM: publishOrigin: ui
5:48:10 PM: plugins:
5:48:10 PM: - inputs: {}
5:48:10 PM: origin: ui
5:48:10 PM: package: '@netlify/plugin-gatsby'
5:48:10 PM: redirects:
5:48:10 PM: - from: /api/* status: 200 to: /.netlify/functions/gatsbyCaching artifacts
5:48:10 PM: Started saving node modules
5:48:10 PM: Finished saving node modules
5:48:10 PM: Started saving build plugins
5:48:10 PM: Finished saving build plugins
5:48:10 PM: Started saving pip cache
5:48:10 PM: Finished saving pip cache
5:48:10 PM: Started saving emacs cask dependencies
5:48:10 PM: Finished saving emacs cask dependencies
5:48:10 PM: Started saving maven dependencies
5:48:10 PM: Finished saving maven dependencies
5:48:10 PM: Started saving boot dependencies
5:48:10 PM: Finished saving boot dependencies
5:48:10 PM: Started saving rust rustup cache
5:48:10 PM: Finished saving rust rustup cache
5:48:10 PM: Started saving go dependencies
5:48:10 PM: Finished saving go dependencies
5:48:10 PM: Build failed due to a user error: Build script returned non-zero exit code: 2
5:48:10 PM: Creating deploy upload records
5:48:10 PM: Failing build: Failed to build site
5:48:10 PM: Failed during stage 'building site': Build script returned non-zero exit code: 2
5:48:10 PM: Finished processing build request in 1m10.645108901s

import CoderapperIcon from "../icons/coderapper.svg"; import TarkalabsIcon from "../icons/tarkalabs.svg"; import RailsfactoryIcon from "../icons/railsfactory.svg"; import Eam360Icon from "../icons/eam360.svg";

plugins: [ gatsby-plugin-react-helmet, "gatsby-plugin-sass", gatsby-plugin-image, gatsby-plugin-sharp, gatsby-transformer-sharp, { resolve: "gatsby-plugin-react-svg", options: { rule: { include: /icons/, }, }, }, ],

Add support for Gatsby V5

Now that Gatsby 5.0.0 is available, it would be good if this plugin could be updated to avoid the following warning:

warn Plugin gatsby-plugin-react-svg is not compatible with your gatsby version 5.0.0 - It requires gatsby@^4.0.0 || ^3.0.0 || ^2.0.0

Thanks, let me know if I can do anything to help?

Error building on Vercel

This plugin works great to build locally, but can't get it building on Vercel

Getting:

Error: Invalid tag: data:image/svg+xml;base64,....

Using this config:

  plugins: [
    {
      resolve: "gatsby-plugin-react-svg",
      options: {
        rule: {
          include: /icons/,
          omitKeys: [],
        },
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `icons`,
        path: `${__dirname}/src/icons`,
      },
    },
  ],

unable to use list-style with imported SVG

I am having trouble attempting to use an .svg as a custom list-style icon. Everything appears to be working as expected except that nothing is visible. Can you please confirm the dev-tools output I'm seeing is what I should expect here? Any pointers gratefully received! Many thanks.

  • svg filepath: src/assets/file.svg

  • gatsby-config.js

{
      resolve: 'gatsby-plugin-react-svg',
      options: {
        rule: {
          include: /assets/,
        },
    },
}
  • component scss
ul {
    list-style: url(../assets/file.svg);
  }
  • dev-tools output for element inspect
ul {
    list-style: url(http://localhost:8000/de/karriere/function ArrowOpenforce (props) {\n return React.createElement(\"svg\",props,[React.createElement(\"path\",{\"d\":\"M14.6122 15.9323L20 12.6493L0 0.466064L14.6122 15.9323Z\",\"fill\":\"#E1B83D\",\"key\":0}),React.createElement(\"path\",{\"d\":\"M14.6125 9.36963L20.0002 12.6492L0.00292969 24.8324L14.6125 9.36963Z\",\"fill\":\"#FFCE44\",\"key\":1})]);\n});
}

Cannot override options>rule>use to render SVG properly

If two svgs have same classes, classes overrides each other:

<!-- should be red - but it's green -->
<svg viewBox="0 0 4 4" style="height: 100px;">
  <style>.circle_class{fill:red;}</style>
  <circle class='circle_class' cx="2" cy="2" r="2"/>
</svg>
<!-- should be green - and it is -->
<svg viewBox="0 0 4 4" style="height: 100px;">
  <style>.circle_class{fill:green;}</style>
  <circle class='circle_class' cx="2" cy="2" r="2"/>
</svg>

To prevent this sitution, svg-react-loader colud add file name as class prefix using 'classIdPrefix' via gatsby-plugin-react-svg this way:

actions.setWebpackConfig({
  module: {
    rules: [
      {
        test: /\.svg$/,
        include,
        exclude,
        ...otherProps,
        use: {
            loader: 'svg-react-loader',
            options: {
                filters,
                classIdPrefix: true
            }
        },
      }
    ],
  }
})

It's impossible now. I see that anything can be passed through via '...otherProps', but 'use' will be overridden anyway.

Mocking Component in Jest

How do you mock these SVG components in Jest?

I import it in my files like suggested, but when it tries to retrieve it I get an error that the Module could not be found.

If I try the suggested Code Transform method from Jest allows the tests to pass, but I get an error because the import ends up being <MyIcon.svg /> which is invalid syntax.

Can we get some documentation on how to test components that use this plugin?

Putting inline SVGs in custom folder

Hey there -- great plugin! I'd like to organize my inline SVGs in a specific folder (/assets/images/inline-svgs/) as I will be using SVGs both inline and as <img>s.

Whenever I try to customize the include path for this plugin in my gatsby-config.js, I get a console error: Invalid tag: data:image/svg+xml...

How can I customize the include path?

Unable to import files with '#' in filename

gatsby-config.js

    {
      resolve: 'gatsby-plugin-react-svg',
      options: {
        rule: {
          include: /duotone-icons-2/
        }
      }
    }

Application Code

import ServicesIcon from '../landkit/img/icons/duotone-icons-2/Shopping/Chart-line#1.svg'

...

<div className='icon icon-sm text-success'>
  <ServicesIcon />
</div>

Gatsby Develop Output:

image

Can't make it work

Hey, Apologies for making another one of these but I've been banging my head against the wall trying to make this work. Using this plugin as it was bundled with the universal starter theme and I have a bunch of SVG icons to import.

File structure is as follows:
SVGs are inside gatsby-portfolio/content/images/icons/
Component I'm trying to import to is in src/components/Container/container.js

Trying to import icons like so :
import CSS3 from './images/icons/css3.svg';

Throwing this error:
Module not found: Error: Can't resolve './images/icons/css3.svg' in '/Users/Me/code/portfolio/gatsby-portfolio/src/components/Container

This is how my gatsby.config looks.
`
{

  resolve: 'gatsby-source-filesystem',

  options: {

    name: 'content',

    path: `${__dirname}/content`,

  },

},

...

{

  resolve: 'gatsby-plugin-react-svg',

  options: {

    rule: {

      include: /images/,

    },

  },

}

`

Any ideas? I appreciate any help thankyou for reading.

Warning: React does not recognize the `rdfResource` prop on a DOM element.

Hi, it's me again,

Appears that using the plugin launch warnings in the console as you can see here:
consolewarningplugin
I think this kind of warning were launch because of xml syntax like "xmlns:cc", "rdf:resource", etc...

So, is it possible to stop these warning still using the plugin or not ?

gatsby -v : 1.1.58

Allow processing only particular SVGs

I'd like the ability to process only SVGs matching a particular filename pattern (such as /\.inline\.svg$/) and leaving others to the existing URL loader.

Is that an option you'd be interested in adding?

[gatsby-plugin-react-svg] Support multiple asset directories

Right now there's only one folder where the plugin will build the SVGs:

plugins: [
  {
    resolve: "gatsby-plugin-react-svg",
    options: {
      rule: {
        include: /assets/ // See below to configure properly
      }
    }
  }
];

It would be great if include accepted an array such that multiple folders can be used.

Issue SVG on Windows

Hey!

We've been using your plugin on our gatsby-starter and it all works fine on OSX, until recently when an user try to run the starter under windows he got an issue:

image

I've been trying to debug and see what's wrong with the plugin but I can't really say,

Thanks in advance,

Image not rendering properly

Description

followed the tutorial as provided and am unable to successfully render an image to the screen using plugin.

Steps to reproduce

  1. installed plugin
  2. added plugin to gatsby-config.js and included images with path inline.svg
  3. imported image and referred to it as a react component, as in tutorial
  4. ran gatsby develop and loaded page, image is not showing, a blank react component is being shown in the code

Dependencies

{
"gatsby-plugin-react-svg": "^2.1.1",
"svg-react-loader": "^0.4.6",
"url-loader": "^1.1.2"
 }

Error on documentation in gatsby-config.js

Hi,
I searched for a solution to this problem for hours but finally found it with my own efforts. While the usage pattern shown in the document in the config file is as below, giving the rule object and regex without using strings creates a problem.

1- remove rule and use include under options
2- put regex expressions between string tags

plugins: [
  {
    resolve: "gatsby-plugin-react-svg",
    options: {
      rule: {
        include: /assets/ // See below to configure properly
      }
    }
  }
];

should be

plugins: [
  {
    resolve: "gatsby-plugin-react-svg",
    options: {
        include: "/assets/"
    }
  }
];

Produced error on documentation way:

Failed to execute 'createElement' on 'Document': The tag name provided ('data:image/svg+xml;base64,PD94bWwgdmV ..... is not a valid name.

Thank you for that great plugin also! 🔥🔥

Edit: I can open a PR on that if you're ok

Two SVGs on the same page interfering

SVGs are rendering very funky. Styling of my SVGs are being distorted, changed, etc. when rendering more than 1 SVG.

This issue is native to the svg-react-loader jhamlet/svg-react-loader#102 and it remains an open issue.

Seeing as it also affects a Gatsby app...

What would be the alternative way to add SVGs in Gatsby?

Is anyone else not having the same issue?

Can't manage to make the plugin work

Hi, I'm building a web app and I would like to use this plugin to use my .svg file on the app but I can't seem to make it works.

The issue I'm getting is InvalidCharacterError: Failed to execute 'createElement' on 'Document': The tag name provided ('http://localhost:8000/static/Blog.7ea27b1f.svg') is not a valid name.

Here is my gatsby-config.js:

module.exports = {
  siteMetadata: {
    title: "Blog"
  },

  plugins: [
    /* ... */ ,

    {
      resolve: "gatsby-plugin-react-svg",
      options: {
        include: "/src/assets/images/"
      }
    }
  ]
};

and here is the file (header.js):

import React from "react";

import HeaderBurger from "./HeaderBurger/HeaderBurger";

import { StyledBar, StyledLink, StyledBrand } from "./Header.styled";

import Blog from "../../../assets/images/Blog.svg";

export default function Header() {
  return (
    <StyledBar>
      <StyledLink to="/" title="Blog">
        <StyledBrand>
          <Blog/>
        </StyledBrand>
      </StyledLink>

      <HeaderBurger />
    </StyledBar>
  );
} 

My working tree is like the next:

  • gatsby-config.js
  • src folder
    • components folder
      • Layout folder
        • Header folder
          • Header.js
  • assets folder
    • images folder
      • blog.js

Version of Gatsby: 1.1.58

I've also tried to import the blog component from "./Blog.svg" and it didn't work.
Can I have a little help on this one please ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.