I'm rewriting the project using babel
and svgo
and you can follow the same on the rewrite branch.
The current branch had regex replaces and it was hard to figure what happens where and hard to reason about bugs. The rewrite has only 2 simple steps
- Optimize SVG using SVGO
- Transform SVG to JS using a babel-plugin
npm i react-svg-loader
This outputs ES6+JSX code and to be used with babel-loader
module.exports = {
loaders: [
{
test: /\.svg$/,
loader: 'babel!react-svg'
}
]
}
of react-svg-loader
import React from 'react';
export default class extends React.Component {
render() {
return <svg>
...
</svg>;
}
}
and this should be passed through babel-loader
All the props are passed onto the root svg element.
import Image from './image.svg';
// ...
<Image width={400} height={200} />
// ...
The ouput svg component takes in options that are defined in the svg
The react-svg-loader comes with a cli (svg2react
) that you can use to convert svg files to react components. Use this tool when you'd want to customize your svg component by hand. Otherwise the loader just works.
`npm bin`/svg2react file1.svg file2.svg
and the following files will be emitted
file1.svg.react.js
file2.svg.react.js
in the SAME directory as the files
- Root element is always
<svg>
- namespace-d attributes (
myns:something
) are stripped - Hyphenated attributes are converted to camelCase. Others are preserved as it is
style
tags are parsed and outputted as objectsroot
's attributes are parsed and overridden by props- Only tags allowed by react are retrieved. Others are simply ignored
- Order of the tags are maintained as it is
- All attributes passed to the generated Component are passed onto the root svg element
MIT License - http://boopathi.mit-license.org