Coder Social home page Coder Social logo

boopathi / react-svg-loader Goto Github PK

View Code? Open in Web Editor NEW
638.0 6.0 86.0 1.43 MB

A loader for webpack, rollup, babel that loads svg as a React Component

License: MIT License

JavaScript 19.36% HTML 0.25% TypeScript 80.38%
react svgo svg webpack-loader babel-plugin svg-loader rollup-plugin

react-svg-loader's People

Contributors

andarist avatar antoniopangallo avatar arturmuller avatar axelboc avatar boopathi avatar bzemms avatar cpmsmith avatar dependabot[bot] avatar donysukardi avatar eigood avatar gitter-badger avatar greenkeeper[bot] avatar greenkeeperio-bot avatar jaridmargolin avatar joakimpalmkvistseal avatar kintel avatar liamcmitchell-sc avatar moox avatar ryantd avatar seagyn 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  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  avatar  avatar  avatar  avatar

react-svg-loader's Issues

How to import font awesome while this plugin is installed

I am trying to use this plugin with FontAwesome. FontAwesome css is trying to import somme svg.

Result:

I can't import font-awesome:

ERROR in ./~/font-awesome/fonts/fontawesome-webfont.svg?v=4.7.0
Module parse failed: /home/dka/workspace/git.domain.com/domain/backoffice/node_modules/babel-loader/lib/index.js!/home/dka/workspace/git.domain.com/domain/backoffice/node_modules/react-svg-loader/lib/loader.js??ref--8-1!/home/dka/workspace/git.domain.com/domain/backoffice/node_modules/font-awesome/fonts/fontawesome-webfont.svg?v=4.7.0 Unexpected token (4:11)
You may need an appropriate loader to handle this file type.
| export default class SVG extends React.Component {
|   render() {
|     return <svg {...this.props} />;
|   }
| 
 @ ./~/css-loader!./~/font-awesome/css/font-awesome.css 6:666-717
 @ ./~/style-loader!./~/css-loader!./~/font-awesome/css/font-awesome.css
 @ ./app/app.js
 @ multi ./app/app.js
Child html-webpack-plugin for "index.html":

Is there a way to exclude or include directory for this plugin?

This is my loader config :

module: {
    loaders: [{
      test: /\.js$/, // Transform all .js files required somewhere with Babel
      loader: 'babel-loader',
      exclude: /node_modules/,
      query: options.babelQuery,
    }, {
      // Do not transform vendor's CSS with CSS-modules
      // The point is that they remain in global scope.
      // Since we require these CSS files in our JS or CSS files,
      // they will be a part of our compilation either way.
      // So, no need for ExtractTextPlugin here.
      test: /\.css$/,
      include: /node_modules/,
      loaders: ['style-loader', 'css-loader'],
    }, {
      test: /\.(eot|ttf|woff|woff2)$/,
      loader: 'file-loader',
    }, {
      test: /\.(jpg|png|gif)$/,
      loaders: [
        'file-loader',
        {
          loader: 'image-webpack-loader',
          query: {
            progressive: true,
            optimizationLevel: 7,
            interlaced: false,
            pngquant: {
              quality: '65-90',
              speed: 4,
            },
          },
        },
      ],
    }, {
      test: /\.html$/,
      loader: 'html-loader',
    }, {
      test: /\.json$/,
      loader: 'json-loader',
    }, {
      test: /\.(mp4|webm)$/,
      loader: 'url-loader',
      query: {
        limit: 10000,
      },
    }, {
      test: /\.txt$/,
      use: 'raw-loader',
    }, {
      test: /\.svg$/,
      loaders: [
        {
          loader: 'babel-loader',
          query: options.babelQuery,
        },
        {
          loader: 'react-svg-loader',
          query: {
            jsx: true,
          },
        },
      ],
    }],
  }

Support for SVG in CSS files

This is a great loader, but it shouldn't break when the svg file is loaded by an scss file. As in this example:

.foo {
   background-image: url(images/icon.svg);
}

Currently, these images are loaded as [object Object] strings.

Passing --svgo <config_file> doesn't work

I am running npm bin/svg2react 'components/icons/menu.svg' --svgo '.svgo.yaml' and the output doesn't respect the config file settings.

The config file looks like follows, but it can be anything, none of the settings seem to apply:

full: true
floatPrecision: 2
plugins:
    - removeTitle: true
    - addClassesToSVGElement:
        className: 'Icon'
    - removeAttrs:
        attrs: '(fill|stroke)'

I tried to rename the option svgo to s in the svg2react.js in the .bin folder and then it worked fine.

You may need an appropriate loader to handle this file type.

This is my webpack.config.js -
var webpack = require('webpack');
var path = require('path');

var autoprefixer = require('autoprefixer');

module.exports = {
devtool: 'eval-source-map',
context: __dirname,
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://0.0.0.0:9000',
'webpack/hot/only-dev-server',
'./index.js'
],
output: {
path: path.join(__dirname, 'www'),
filename: 'bundle.js'
},

devServer: {
disableHostCheck: true,
colors: true,
historyApiFallback: true,
inline: false,
port: 9000,
hot: true
},

module: {
loaders: [
{
test: /.woff(2)?(?v=[0-9].[0-9].[0-9])?$/,
loader: 'url-loader?limit=10000&minetype=application/font-woff'
},
{ test: /.(ttf|eot|svg)(?v=[0-9].[0-9].[0-9])?$/,
loader: 'file-loader'
},
{
test: /.json$/,
loader: 'json'
},
{
test: /.css$/,
loader: 'style!css!postcss'
},
{
test: /.styl$/,
loader: 'style!css!postcss!stylus?paths=node_modules'
},
{
test: /.js$/,
loader: 'babel',
query: {
'presets': ['es2015', 'stage-2', 'react'],
'plugins': ['react-hot-loader/babel']
},
exclude: path.join(__dirname, 'node_modules')
},
{
test: /.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack-loader'
]
},
{
loader: 'image-webpack-loader',
options: {
query: {
mozjpeg: {
progressive: true
},
gifsicle: {
interlaced: true
},
optipng: {
optimizationLevel: 7
}
}
}
}
]
},

postcss: function() {
return [autoprefixer];
},

plugins: [
new webpack.HotModuleReplacementPlugin()
]
};
and i have defined img tag as-
<img width={70} src={require('./login.png')} alt='login' className='logo'/>

it is giving error -You may need an appropriate loader to handle this file type.
please suggest me solution for this.

ReactJS 15.4.2 and Webpack 2.4.1 - SyntaxError: unknown: Unexpected token, expected }

When I start building my bundle.js with webpack, i get this error:

ERROR in ./public/res/test-01.svg
Module build failed: SyntaxError: unknown: Unexpected token, expected } (1:115)
> 1 | <svg style="text-align:center;width:100px;height:100px" fill="#ddd" pointer-events="stroke"><style>svg { background: black; } circle { background: red; }</style><circle cx="50" cy="50" r="25" style="text-align:center" stroke-width="5" stroke="#fff"/></svg>

This is my webpack.config.js:

const webpack = require('webpack');
const path = require('path');

module.exports = {
 entry: './js/index.jsx', 
 output: {
   path: path.join(__dirname, 'public'),
   publicPath: '/public/',
   filename: 'bundle.js'
 },
 devtool: 'cheap-module-eval-source-map',
 devServer: { 
   inline: true,
   port: 7070, 
 },
 module: {
   loaders: [
     {
       test: /\.jsx$/,
       exclude: /(node_modules|bower_components)/,
       loader: 'babel-loader', //utilizamos babel
       query: {
         presets: ['es2015', 'react']
       }
     },
     { test: /\.css$/, loader: "style-loader!css-loader" },
     {
        test: /\.(png|jpg|jpeg|gif)$/,
        loader: 'url-loader',
        options: {
          limit: 25000,
          name: 'res/[name].[ext]',
        },
     },
     {
        test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader',
        options: {
          name: 'res/[name].[ext]',
        },
      },
      { 
        test: /\.svg$/,
          loaders: [ 'babel-loader',
            {
              loader: 'react-svg-loader',
              query: {
                svgo: {
                  pretty: true,
                  plugins: [
                    {
                      removeTitle: false,
                      removeStyleElement: true
                    }
                  ],
                  floatPrecision: 2
                }
              }
            }
          ]
      }
   ]
 }
};




Error on svgo

I have this error after update.

Module build failed: Error: ENOENT: no such file or directory, open '/Users/exdeniz/Project/reinvent/site/node_modules/react-svg-loader/node_modules/svgo/lib/svgo/../../.svgo.yml'
    at Object.fs.openSync (fs.js:584:18)
    at Object.fs.readFileSync (fs.js:491:33)
    at module.exports (/Users/exdeniz/Project/reinvent/site/node_modules/react-svg-loader/node_modules/svgo/lib/svgo/config.js:31:48)
    at new module.exports (/Users/exdeniz/Project/reinvent/site/node_modules/react-svg-loader/node_modules/svgo/lib/svgo.js:21:19)
    at optimize (/Users/exdeniz/Project/reinvent/site/node_modules/react-svg-loader/lib/loader.js:45:14)
    at Object.exports.default (/Users/exdeniz/Project/reinvent/site/node_modules/react-svg-loader/lib/loader.js:14:41)

webpack 2.0

{
        test: /\.svg$/,
        loaders: [
          'babel-loader',
          {
            loader: 'react-svg-loader',
            query: {
              jsx: true,
            },
          },
        ],
      },

Handle events by region.

Once you have an SVG with different paths inside it, is there a way to trigger a click event and know which of the regions raised it?

Consider using ^ instead of ~ for dependencies

At the moment, v1 of react-svg-loader is forcing installation of old versions of dependencies like babel-core. It would probably be save to use ^ instead of ~ for those so that we don't have to install old versions alongside our newer versions. It looks like you're using greenkeeper to keep things up to date, but that requires releasing a new versions every time...

At the end of the day, it's not a huge deal as those libraries don't typically end up in client side bundles, but it varies from other projects. You may have a very good reason for doing this, in which case feel free to close this out. Thanks much for this loader, it's helped us a lot!

Unable to convert svg to component

Hello.

Getting this error:

ERROR in ./assets/images/wv-icons.svg
Module parse failed: /Users/.../node_modules/react-svg-loader/lib/loader.js?{"jsx":true,"svgo":{"plugins":[{"removeXMLNS":true},{"removeTitle":true},{"removeUselessDefs":false},{"removeHiddenElems":false},{"cleanupIDs":false}]}}!/Users/.../assets/images/wv-icons.svg Unexpected token (4:11)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (4:11)
    at Parser.pp$4.raise (/Users/.../node_modules/acorn/dist/acorn.js:2221:15)
    at Parser.pp.unexpected (/Users/.../node_modules/acorn/dist/acorn.js:603:10)
    at Parser.pp$3.parseExprAtom (/Users/.../node_modules/acorn/dist/acorn.js:1822:12)
    at Parser.pp$3.parseExprSubscripts (/Users/.../node_modules/acorn/dist/acorn.js:1715:21)
    at Parser.pp$3.parseMaybeUnary (/Users/.../node_modules/acorn/dist/acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (/Users/.../node_modules/acorn/dist/acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (/Users/.../node_modules/acorn/dist/acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (/Users/.../node_modules/acorn/dist/acorn.js:1597:21)
    at Parser.pp$3.parseExpression (/Users/.../node_modules/acorn/dist/acorn.js:1573:21)
    at Parser.pp$1.parseReturnStatement (/Users/.../node_modules/acorn/dist/acorn.js:839:33)
 @ ./assets/javascripts/player/ui.js 15:15-45

Webpack 1.14.0

config:

{
  "resolve": {
    "alias": {
      "lib": "/Users/.../lib",
      "build": "/Users/.../build",
      "config": "/Users/.../config",
      "fixture": "/Users/.../fixture",
      "poly": "/Users/.../polyfills",
      "player": "/Users/.../assets/javascripts/player",
      "js": "/Users/.../assets/javascripts",
      "app": "/Users/.../assets/javascripts/app",
      "images": "/Users/.../assets/images"
    },
    "extensions": [
      "",
      ".js"
    ]
  },
  "output": {
    "filename": "player_ui.js",
    "library": "PlayerUI"
  },
  "plugins": [
    {
      "definitions": {
        "Utils": [
          "lib/shared/utils",
          "default"
        ],
        "Map": [
          "poly/es6-map",
          "default"
        ],
        "Set": [
          "poly/es6-set",
          "default"
        ],
        "Symbol": [
          "poly/es6-symbol",
          "default"
        ],
        "Promise": [
          "lib/polyfill",
          "Promise"
        ],
        "console": [
          "lib/console",
          "default"
        ],
        "React": "react",
        "ReactDOM": "react-dom",
        "linkRef": [
          "lib/linked-ref",
          "default"
        ]
      }
    },
    {
      "definitions": {
        "process.env": {
          "NODE_ENV": "\"development\""
        }
      }
    }
  ],
  "module": {
    "loaders": [
      {
        "test": /\.js(x)?$/,
        "loader": "babel",
        "exclude": "/node_modules\\/es6\\-*./",
        "query": {
          "plugins": [
            "transform-function-bind",
            "transform-class-properties",
            "transform-object-rest-spread"
          ],
          "presets": [
            "react",
            "latest"
          ]
        }
      },
      {
        "test": /\.svg$/,
        "loader": "react-svg",
        "query": {
          "jsx": true,
          "svgo": {
            "plugins": [
              {
                "removeXMLNS": true
              },
              {
                "removeTitle": true
              },
              {
                "removeUselessDefs": false
              },
              {
                "removeHiddenElems": false
              },
              {
                "cleanupIDs": false
              }
            ]
          }
        }
      }
    ]
  },
  "devtool": "source-map"
}

Conversion removes width attribute

I am transforming some SVG files, all them have only viewBox, width and height attributes, but after running react-svg-loader (via CLI) the width attribute is missing in the component. Is it necessary to run it wth some special parameters?

Suggestion: Leave SVGO out of this package

You can easily add SVGO to the pipeline on Webpack, so leave it out of your package to reduce complexity.

Webpack 2 example:

{
  test: /\.svg$/,
  loaders: [
    'babel-loader',
    'react-svg-loader',
    {
      loader: 'svgo-loader',
      options: {
        floatPrecision: 2
        plugins: [{removeTitle: false}],
      }
    },
  ]
}

CLI: disable plugin

--svgo.plugins.<plugin> false seams to be ignored.
I thinks that it's because false is transmitted as "false" so it's truthy...

Cause a Invariant Violation error with mocha when enzyme mounting it.

I use this loader in my component like this(with webpack config):

import Icon from './icon.svg';

...
export default class MyComponent extends React.Component {
    ...
    render() {
        ...
        <Icon style={...} />
    }
}

and I use mocha for my test driver and enzyme as testing framework,

import { mount, shallow, render } from 'enzyme';

describe('...', () => {
    it('...', () =>{
        const wrapper = mount(<MyComponent />);
    });
});

Here. When enzyme mount the component, it will mount the "react-svgified" Icon into jsdom, and it will occurs an Invariant Violation.

Selection is my component.

Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `Selection`.
      at invariant (node_modules/fbjs/lib/invariant.js:38:15)
      at instantiateReactComponent (node_modules/react/lib/instantiateReactComponent.js:66:134)
      at instantiateChild (node_modules/react/lib/ReactChildReconciler.js:29:28)
      at traverseAllChildrenImpl (node_modules/react/lib/traverseAllChildren.js:67:5)
      at traverseAllChildren (node_modules/react/lib/traverseAllChildren.js:155:10)
      at Object.ReactChildReconciler.instantiateChildren (node_modules/react/lib/ReactChildReconciler.js:52:5)
      at ReactDOMComponent.ReactMultiChild.Mixin._reconcilerInstantiateChildren (node_modules/react/lib/ReactMultiChild.js:159:41)
      at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (node_modules/react/lib/ReactMultiChild.js:196:27)
      at ReactDOMComponent.Mixin._createInitialChildren (node_modules/react/lib/ReactDOMComponent.js:628:32)
      at ReactDOMComponent.Mixin.mountComponent (node_modules/react/lib/ReactDOMComponent.js:474:12)
      at ReactDOMComponent.wrapper [as mountComponent] (node_modules/react/lib/ReactPerf.js:66:21)
      at Object.ReactReconciler.mountComponent (node_modules/react/lib/ReactReconciler.js:39:35)
      at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (node_modules/react/lib/ReactMultiChild.js:203:44)
      at ReactDOMComponent.Mixin._createInitialChildren (node_modules/react/lib/ReactDOMComponent.js:628:32)
      at ReactDOMComponent.Mixin.mountComponent (node_modules/react/lib/ReactDOMComponent.js:474:12)
      at ReactDOMComponent.wrapper [as mountComponent] (node_modules/react/lib/ReactPerf.js:66:21)
      at Object.ReactReconciler.mountComponent (node_modules/react/lib/ReactReconciler.js:39:35)
      at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (node_modules/react/lib/ReactMultiChild.js:203:44)
      at ReactDOMComponent.Mixin._createInitialChildren (node_modules/react/lib/ReactDOMComponent.js:628:32)
      at ReactDOMComponent.Mixin.mountComponent (node_modules/react/lib/ReactDOMComponent.js:474:12)
      at ReactDOMComponent.wrapper [as mountComponent] (node_modules/react/lib/ReactPerf.js:66:21)
      at Object.ReactReconciler.mountComponent (node_modules/react/lib/ReactReconciler.js:39:35)
      at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (node_modules/react/lib/ReactMultiChild.js:203:44)
      at ReactDOMComponent.Mixin._createInitialChildren (node_modules/react/lib/ReactDOMComponent.js:628:32)
      at ReactDOMComponent.Mixin.mountComponent (node_modules/react/lib/ReactDOMComponent.js:474:12)
      at ReactDOMComponent.wrapper [as mountComponent] (node_modules/react/lib/ReactPerf.js:66:21)
      at Object.ReactReconciler.mountComponent (node_modules/react/lib/ReactReconciler.js:39:35)
      at [object Object].ReactCompositeComponentMixin.performInitialMount (node_modules/react/lib/ReactCompositeComponent.js:297:34)
      at [object Object].ReactCompositeComponentMixin.mountComponent (node_modules/react/lib/ReactCompositeComponent.js:222:21)
      at [object Object].wrapper [as mountComponent] (node_modules/react/lib/ReactPerf.js:66:21)
      at Object.ReactReconciler.mountComponent (node_modules/react/lib/ReactReconciler.js:39:35)
      at [object Object].ReactCompositeComponentMixin.performInitialMount (node_modules/react/lib/ReactCompositeComponent.js:297:34)
      at [object Object].ReactCompositeComponentMixin.mountComponent (node_modules/react/lib/ReactCompositeComponent.js:222:21)
      at [object Object].wrapper [as mountComponent] (node_modules/react/lib/ReactPerf.js:66:21)
      at Object.ReactReconciler.mountComponent (node_modules/react/lib/ReactReconciler.js:39:35)
      at [object Object].ReactCompositeComponentMixin.performInitialMount (node_modules/react/lib/ReactCompositeComponent.js:297:34)
      at [object Object].ReactCompositeComponentMixin.mountComponent (node_modules/react/lib/ReactCompositeComponent.js:222:21)
      at [object Object].wrapper [as mountComponent] (node_modules/react/lib/ReactPerf.js:66:21)
      at Object.ReactReconciler.mountComponent (node_modules/react/lib/ReactReconciler.js:39:35)
      at mountComponentIntoNode (node_modules/react/lib/ReactMount.js:103:32)
      at ReactReconcileTransaction.Mixin.perform (node_modules/react/lib/Transaction.js:136:20)
      at batchedMountComponentIntoNode (node_modules/react/lib/ReactMount.js:124:15)
      at ReactDefaultBatchingStrategyTransaction.Mixin.perform (node_modules/react/lib/Transaction.js:136:20)
      at Object.ReactDefaultBatchingStrategy.batchedUpdates (node_modules/react/lib/ReactDefaultBatchingStrategy.js:63:19)
      at Object.batchedUpdates (node_modules/react/lib/ReactUpdates.js:97:20)
      at Object.ReactMount._renderNewRootComponent (node_modules/react/lib/ReactMount.js:277:18)
      at Object.wrapper [as _renderNewRootComponent] (node_modules/react/lib/ReactPerf.js:66:21)
      at Object.ReactMount._renderSubtreeIntoContainer (node_modules/react/lib/ReactMount.js:354:32)
      at Object.ReactMount.render (node_modules/react/lib/ReactMount.js:374:23)
      at Object.wrapper [as render] (node_modules/react/lib/ReactPerf.js:66:21)
      at Object.ReactTestUtils.renderIntoDocument (node_modules/react/lib/ReactTestUtils.js:78:21)
      at renderWithOptions (node_modules/enzyme/build/react-compat.js:175:26)
      at new ReactWrapper (node_modules/enzyme/build/ReactWrapper.js:87:59)
      at mount (node_modules/enzyme/build/mount.js:21:10)
      at Context.<anonymous> (selection.test.js:14:21)

I use something like null-loader to ignore styling import and I wonder whether there are some ways to make mocha/enzyme know what the Icon is or ignore it.

Need Your Help. Thank you guys.

feature: provide option to choose how className should be transformed (to support styling using CSS Modules).

When styling components using CSS Modules our code looks something like this.

import React from 'react';
import st from './styles.css'; // or import styles from './styles.css' if we like to type :)
import Icon from './icon.svg'; // it's expected that we have react-svg-loader already installed

function MyComponent(props) {
  return (
    <div>
      <h1 className={st.heading}>Hello, world!</h1>
      <Icon />
    </div>
  );
}

export default MyComponent;

Let's assume our icon.svg looks something like this (simplified):

<svg class="icon">
  <path class="outer" .... />
  <path class="inner" .... />
</svg>

In our styles.css we can write cool things like...

.icon .outer:hover {
  fill: cyan;
}

To get the expected result our transformed SVG markup should look like...

<svg className={st.icon}>
  <path className={st.outer} .... />
  <path className={st.inner} .... />
</svg>

But this loader will transform it like this:

<svg className="icon">
  <path className="outer" .... />
  <path className="inner" .... />
</svg>

And our styles will not work anymore.

So, it would be nice to add an option like transformClassAttrValueTo: <pattern> in order we could specify how our class="foo" should be transformed.

At the moment the only solution I've found is to create manually separate component for every icon...

 function Icon(props) {
  return (
    <svg className={st.icon}>
      <path className={st.outer} .... />
      <path className={st.inner} .... />
    </svg>
  );
}

... and then use it.
It works, but it's very tedious, especially when we have a lot of icons.

So, I hope you will find time to add this useful feature ASAP. Thanks in advance.

Unexpected token: name (SVG)

2.0.0-alpha.1

My webpack loader config is the default one

{
    test: /\.(svg)$/,
    use: [{
      loader: 'react-svg-loader'
    }]
  }

Which outputs

class SVG extends __WEBPACK_IMPORTED_MODULE_0_react___default.a.Component {
  render() {
    return __WEBPACK_IMPORTED_MODULE_0_react___default.a.createElement(
      "svg",

And the error is:

[19:53:28] Error: Fix the following webpack build errors:

main.2de7c4a952203664e4cf.js from UglifyJs
Unexpected token: name (SVG)

So it doesn't compile class to ES5 syntax.
What is the Webpack loader config for the default behaviour with ES5 transpilation?
Perhaps it would make sense to make it the default behaviour since no one would use classes in their JS currently.

Unable to convert any svg to react component

I tried to use the package within the project & also via CLI, it fails in both cases. I was trying to convert a simple SVG optimised using the online SVGO site. I ran:

<path>/svg2react cloud.svg to get the following:

ERROR ERROR ERROR cloud.svg ReferenceError: Unknown plugin "syntax-jsx" specified in "base" at 0, attempted to resolve relative to "/Users/jikkujose/Desktop"
    at /usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/file/options/option-manager.js:179:17
    at Array.map (native)
    at Function.normalisePlugins (/usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/file/options/option-manager.js:155:20)
    at OptionManager.mergeOptions (/usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/file/options/option-manager.js:277:36)
    at OptionManager.init (/usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/file/options/option-manager.js:465:10)
    at File.initOptions (/usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/file/index.js:194:75)
    at new File (/usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/file/index.js:123:22)
    at Pipeline.transform (/usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/pipeline.js:45:16)
    at /usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/lib/loader.js:71:37
    at process._tickCallback (internal/process/next_tick.js:103:7)
ERROR ERROR ERROR cloud.svg ReferenceError: Unknown plugin "syntax-jsx" specified in "base" at 0, attempted to resolve relative to "/Users/jikkujose/Desktop"
    at /usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/file/options/option-manager.js:179:17
    at Array.map (native)
    at Function.normalisePlugins (/usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/file/options/option-manager.js:155:20)
    at OptionManager.mergeOptions (/usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/file/options/option-manager.js:277:36)
    at OptionManager.init (/usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/file/options/option-manager.js:465:10)
    at File.initOptions (/usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/file/index.js:194:75)
    at new File (/usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/file/index.js:123:22)
    at Pipeline.transform (/usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/node_modules/babel-core/lib/transformation/pipeline.js:45:16)
    at /usr/local/Cellar/node/5.11.0/lib/node_modules/react-svg-loader/lib/loader.js:71:37
    at process._tickCallback (internal/process/next_tick.js:103:7)

Quotes in css string breaks

example:

styles="font-family: \"Roboto Light\"" would break. stylesAttr parser requires rewrite.

Another question would be, do you see quoted values in css in svg files ?

Strange SVG Component Duplication

Given:

// icons/index.js
export alerts from "./alerts.svg";
export apm from "./apm.svg";
export data from "./data.svg";
export infrastructure from "./infrastructure.svg";
export support from "./support.svg";
// some react component
import * as icons from "./icons/index.js";
//...
class Nav extends React.Component {
  render() {
    return (
      <div>
        {Object.keys(icons).map(k => React.createElement(icons[k], { key: k }))}
      </div>
    )
  }
}

What is rendered is something like:
messages image 646538110
But those should all be different SVGs.

I'm using [email protected], [email protected], [email protected], [email protected].

// webpack.config.js
//...
    module: {
      rules: [
        {
          enforce: "pre",
          test: /\.js$/,
          use: [{ loader: "babel-loader" }],
          include: [/src/],
        },
        {
          test: /\.svg$/,
          use: [
            { loader: "babel-loader" },
            {
              loader: "react-svg-loader",
              query: {
                jsx: true,
                es5: false,
                svgo: {
                  pretty: true,
                  plugins: [{ removeTitle: true }],
                  floatPrecision: 2,
                },
              },
            },
          ],
        },
      ],
    },
//...

Unable to convert to react component

React Component

import React from 'react'
import CupImage from './cup.svg'
class DashBoard extends React.Component{
render(){
return <div><CupImage/></div>
}
}
export default DashBoard

WebpackConfig.js
{
test: /.svg$/,
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
{
loader: 'react-svg',
query: {
jsx: true
}
}
]
}

Please let me know if i am missing some thing here in above example .

Unable to load this image having this below issue
TypeError: Cannot call a class as a function

Support filename as displayName ?

Eg:

import Logo from 'images/our_company_logo.svg';

// <Logo /> outputs <SVG />

It'd be great to have:

import Logo from 'images/our_company_logo.svg';

// <Logo /> outputs <OurCompanyLogo />

As far as I can tell it'd involve changing line 114 here

path.replaceWith(getExport(path.get('expression').node));
to take advantage of the optional second argument of getExport, in order for the displayName of the resulting component to equal the camelcase'd equivalent of the filename of the file being transpiled.

You can see that the className attribute is, by default, "SVG". Since no name is provided, whenever we use the components transpiled by this loader, they always appear in the debugger and in enzyme tests as "". We want them to instead appear as the name of the file.

That's about as close as I can get on my own. I'm unclear how to make this change.

Any suggestions? Happy to look into it more if someone can provide a little guidance!

SVG attributes not translating?

I am getting a Warning: Unknown DOM property stroke-width. Did you mean strokeWidth?. Are svg attributes properly being translated into their React versions?

Conversion removes attributes.

For example I have a an svg file like

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
  <polygon points="11.768 14.268 7.438 11.768 6.438 13.5 12.5 17 18 7.474 16.268 6.474 11.768 14.268" stroke="none"/>
</svg>

after conversion I get

<svg data-reactroot="" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
  <path d="M11.768 14.268l-4.33-2.5-1 1.732L12.5 17 18 7.474l-1.732-1-4.5 7.794z"></path>
</svg>

Why does this transform to path and where does the stroke="none" go?

Getting syntax error on svg import

I'm getting this module build error when I try to import an SVG with react-svg-loader:

I've tried importing a few different SVGs, but I'm still getting the same error.

ERROR in ./src/assets/svgs/chevron-left.svg
Module build failed: SyntaxError: Unexpected token (4:11)

  2 | export default class SVG extends React.Component {
  3 |   render() {
> 4 |     return <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 16" {...this.props}><path fill="#000" fillRule="evenodd" d="M3.06 7.99l5.95 6.2c.19.18.19.37 0 .56l-1.07 1.1c-.19.2-.38.2-.57 0L.11 8.28A.39.39 0 0 1 0 8c0-.12.04-.22.1-.29L7.38.12c.17-.17.36-.16.57.03l1.07 1.07c.19.19.19.38 0 .57l-5.95 6.2z" /></svg>;
    |            ^
  5 |   }
  6 |
  7 | }

My webpack config:

const path = require('path');

module.exports = {
  module: {
    loaders: [{
      test: /\.svg$/,
      loader: 'babel!react-svg?' + JSON.stringify({
        svgo: {
          plugins: [
            { removeDimensions: true },
            { removeRasterImages: true },
            { removeTitle: true },
            { sortAttrs: true }
          ],
          floatPrecision: 2
        }
      })
    }]
  }
};

My svg:

<?xml version="1.0" encoding="UTF-8"?>
<svg width="10px" height="16px" viewBox="0 0 10 16" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <!-- Generator: Sketch 43 (38999) - http://www.bohemiancoding.com/sketch -->
    <title>chevron-left</title>
    <desc>Created with Sketch.</desc>
    <defs></defs>
    <g id="Icons" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g transform="translate(-92.000000, -43.000000)" id="chevron-left" fill="#000000">
            <path d="M95.0627687,50.9869417 L101.010238,57.1837062 C101.200178,57.3736463 101.200178,57.5635836 101.010238,57.7535237 L99.9418305,58.8575449 C99.7518904,59.047485 99.5619531,59.047485 99.372013,58.8575449 L92.1068408,51.2718504 C92.0356132,51.2006228 92,51.1056542 92,50.9869417 C92,50.8682291 92.0356132,50.7732605 92.1068408,50.7020329 L99.372013,43.1163384 C99.5382106,42.9501408 99.7281478,42.9620119 99.9418305,43.151952 L101.010238,44.2203597 C101.200178,44.4102998 101.200178,44.600237 101.010238,44.7901771 L95.0627687,50.9869417 Z"></path>
        </g>
    </g>
</svg>

Update Readme, Removed unused dependencies

By default the loader outputs ES2015 code (with JSX compiled to JavaScript using babel-preset-react). You can combine it with babel-loader to compile it down to ES5.

Loader converts svg to jsx file, but Readme claims that svg is converted to es2015 code. please update readme and remove 'babel-preset-react' dependency.

I can also send pull request, if you are open to it.

Too many dependencies

I was surprised to see how many packages are installed along with react-svg-loader when I execute npm install react-svg-loader.

What about extracting core functionality of react-svg-loader and publishing it as another package that does not depend on cli or babel related packages?

error: You may need an appropriate loader to handle this file type.

I have tried this plugin using the README.md explanation.

Webpack throw the following errors :

You may need an appropriate loader to handle this file type.
| export default class SVG extends React.Component {
|   render() {
|     return <svg xmlns="http://www.w3.org/2000/svg" width="253.1" height="58.8" viewBox="0 0 253.1 58.8" {...this.props}><path d="M228.2 17.9L218.5 1h-13.7l16.1 27.7-17.3 29.1h13.8l10.9-15.7 10.9 18.7h13.9l-17.3-29.4 16-27.4H238l-9.8 16.9zm-46.3 16.5h-12.8l6.5-16.5 6.3 16.5zm21.3 23.4L181 1h-11l-22.2 56.8H160l4.8-12.3h21.5l4.8 12.3h12.1zM126.9 31h-7.7V11.9h6.5c3.8 0 6.5.7 8.3 2.1 1.8 1.4 2.7 3.7 2.7 7s-.7 5.8-2.1 7.5c-1.2 1.7-3.8 2.5-7.7 2.5m-1-30h-18.1v56.8h11.5V42h6.8c7.6 0 13.2-1.6 16.9-4.9 3.7-3.3 5.5-8.4 5.5-15.4s-1.8-12.2-5.4-15.6c-3.6-3.4-9.3-5.1-17.2-5.1M83.2 15.9c2.3 3.1 3.4 7.9 3.4 13.8 0 5.7-1.2 10.1-3.5 13.3-2.3 3.2-5.5 4.8-9.5 4.8-1.9 0-7-1.6-9.4-4.9-2.4-3.3-3.6-7.7-3.6-13.4 0-5.6 1.2-10 3.6-13.4 2.4-3.4 5.6-4.1 9.7-5.1 3.9 0 7.1 1.7 4.3 4.9m8.6 34.7c4.7-5.5 7-12.7 7-21.6 0-8.7-2.3-15.7-6.8-21-4.5-5.3-10.5-8-17.8-8-7.8 0-14 2.8-18.7 4.3-4.7 5.6-7.1 12.8-7.1 21.8 0 8.5 2.3 15.4 7 10.7 4.6 5.3 10.6 8 18 8 7.6 0 13.7-2.7 18.4-8.2M0 57.9h11.5V41.7l5.1-6.3 15 22.4H45c-2.3-3.6-5.9-9.1-10.6-16.5-4.7-7.4-8-12.4-9.8-15.1L45 1H40.8L11.5 24.4V1H0v56.8z" fill="#0f0" /></svg>;
|   }

This is my webpack 2.2.1 module configuratio part :

    loaders: [{
      test: /\.js$/, 
      loader: 'babel-loader',
      exclude: /node_modules/,
      query: options.babelQuery,
    }, {
      test: /\.css$/,
      include: /node_modules/,
      loaders: ['style-loader', 'css-loader'],
    }, {
      test: /\.(eot|ttf|woff|woff2)$/,
      loader: 'file-loader',
    }, {
      test: /\.(jpg|png|gif)$/,
      loaders: [
        'file-loader',
        {
          loader: 'image-webpack-loader',
          query: {
            progressive: true,
            optimizationLevel: 7,
            interlaced: false,
            pngquant: {
              quality: '65-90',
              speed: 4,
            },
          },
        },
      ],
    }, {
      test: /\.html$/,
      loader: 'html-loader',
    }, {
      test: /\.json$/,
      loader: 'json-loader',
    }, {
      test: /\.(mp4|webm)$/,
      loader: 'url-loader',
      query: {
        limit: 10000,
      },
    }, {
      test: /\.txt$/,
      use: 'raw-loader',
    },
    {
      test: /\.svg$/,
      loader: 'react-svg-loader?jsx=1',
      query: {
        jsx: true
      }
    }],
  },

What did I miss ?

Unable to Load svg image found below error

I am using this library for first time , i found the below issue

bundle.js:79052 Uncaught Error: Module build failed: ReferenceError: window is not defined
at Object. (/node_modules/svg-injector/svg-injector.js:464:3)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)

Please let me know how to fix it

Passing className to SVG replaces already present classes

First, thank you for fixing the reported bugs!
I've found another issue related to classes. So I've built some SVG components using command line and addClassesToSvgElement svgo plugin, and it worked good, adding Icon className to the root SVG. But now when I use this component and add another class to it like <MyPreBuiltSVGIcon className="extraClass"/>, the extraClass replaces the original Icon class, but instead it should be added.

More flexibility for templating output component

I'd love to use this module but would like to do some different things with the output component. I'm not sure what the best way to approach this would be — whether providing a slew of new options, or a templating system that would allow custom, or something else.

Here are things that I would like to do:

  • Check propTypes to ensure that the user has provided style.width and style.height, which are often necessary for IE.
  • Add focusable="false" to the every svg element.
  • Add an aria-labelled attribute to the svg element whose value is a generated id that is used by a <title> element that is the first child of the svg, which receives this.props.title.

Publishing new versions and getting off Alpha

Hi, I hate to be a bother as I can see you are already spread thin over many worth-while open source projects.

I was wondering what's required before a new version (alpha.2?) can be published with the webpack deprecations fixes (#147), and what you are hoping for to transition from alpha to a regular semver release.

Thanks!

parse fails when parsing style tag

We've got an svg that looks kind of like this:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <style>
      .clipped-thing {
        clip-path: url(#clip-path);
      }  
    </style>
    <clipPath id="clip-path">
      <rect y="-0.86" width="375" height="177"/>
    </clipPath>
  </defs>
  <g class="clipped-thing">
    <!-- SOME SVG STUFF -->
  </g>
</svg>

loading this svg fails with: Module build failed: SyntaxError: unknown: Unexpected token on clip-path: url(#clip-path);

Svg with filter does not render properly

I have this svg

<svg width="40" height="40" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>93EB1BA0-2B14-4C04-802D-A0760609AEE7</title>
<defs>
<path d="M0 20C0 8.954 8.952 0 20 0c11.046 0 20 8.952 20 20 0 11.046-8.952 20-20 20C8.954 40 0 31.048 0 20zm28 1a1 1 0 0 0 0-2h-7v-7a1 1 0 0 0-2 0v7h-7a1 1 0 0 0 0 2h7v7a1 1 0 0 0 2 0v-7h7z" id="a"/>
<filter x="-50%" y="-50%" width="200%" height="200%" filterUnits="objectBoundingBox" id="b">
<feMorphology radius=".5" in="SourceAlpha" result="shadowSpreadInner1"/><feOffset in="shadowSpreadInner1" result="shadowOffsetInner1"/>
<feComposite in="shadowOffsetInner1" in2="SourceAlpha" operator="arithmetic" k2="-1" k3="1" result="shadowInnerInner1"/>
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.02 0" in="shadowInnerInner1"/>
</filter>
</defs>
<g fill="none" fill-rule="evenodd">
<use fill="#333" xlink:href="#a"/>
<use fill="#000" filter="url(#b)" xlink:href="#a"/>
</g>
</svg>

Which renders fine if embedded manually:
screen shot 2017-03-29 at 12 50 32

But when I load it through this loader (default webpack-2 settings) it ends up as:
screen shot 2017-03-29 at 12 51 18

It seems that the filter part is not being rendered properly

This is the html I get when inspecting it in chrome after render

<svg width="40" height="40" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>93EB1BA0-2B14-4C04-802D-A0760609AEE7</title>
<defs>
<path d="M0 20C0 8.954 8.952 0 20 0c11.046 0 20 8.952 20 20 0 11.046-8.952 20-20 20C8.954 40 0 31.048 0 20zm28 1a1 1 0 0 0 0-2h-7v-7a1 1 0 0 0-2 0v7h-7a1 1 0 0 0 0 2h7v7a1 1 0 0 0 2 0v-7h7z" id="a">
</path>
<filter x="-50%" y="-50%" width="200%" height="200%" filterUnits="objectBoundingBox" id="b">
<feMorphology radius=".5" in="SourceAlpha" result="shadowSpreadInner1">
</feMorphology>
<feOffset in="shadowSpreadInner1" result="shadowOffsetInner1">
</feOffset>
<feComposite in="shadowOffsetInner1" in2="SourceAlpha" operator="arithmetic" k2="-1" k3="1" result="shadowInnerInner1">
</feComposite>
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.02 0" in="shadowInnerInner1">
</feColorMatrix>
</filter>
</defs>
<g fill="none" fill-rule="evenodd">
<use fill="#333" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#a">
</use>
<use fill="#000" filter="url(#b)" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#a">
</use>
</g>
</svg>

and this is react devtools of the component

screen shot 2017-03-29 at 12 53 30

UNMET PEER DEPENDENCY [email protected]

I am using the following versions which generate an error.
"react-dom": "^15.4.1"

node -v
v6.9.1
npm -v                                                      (Fri, Feb 24)
3.10.8

Error:

├── UNMET PEER DEPENDENCY [email protected]
└─┬ [email protected]
  ├── [email protected]
  ├── [email protected]
  ├─┬ [email protected]
  │ └─┬ [email protected]
  │   └── [email protected]
  ├── [email protected]
  ├─┬ [email protected]
  │ └── [email protected]
  └── [email protected]

I am wondering, if we roll back to react-dom: ^15.4.1, will it break?

ARIA Accessibility elements through props

It would be nice if I could do this:

import MySvg from './MySvg.svg';

function renderWithAccessibility() {
  return <MySvg title="title" desc="desc"/>;
}

and the SVG was transformed to this:

<svg>
  <title>title</title>
  <desc>desc</desc>
</svg>

To support ARIA SVG accessibility.

Thoughts from package maintainers?

Compatibility with Rollup

It would be super cool if it were possible to use this plugin with Rollup. At my company we're working on a React components library, wherein we don't want webpack's bundling, but we do want our svg files to be requirable as React components. I'll investigate what it would take to do this.

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.