airbnb / babel-plugin-inline-react-svg

A babel plugin that optimizes and inlines SVGs for your React Components.
MIT License
474 stars 92 forks source link

babel-plugin-inline-react-svg

Transforms imports to SVG files into React Components, and optimizes the SVGs with SVGO.

For example, the following code...

import React from 'react';
import CloseSVG from './close.svg';

const MyComponent = () => <CloseSVG />;

will be transformed into...

import React from 'react';
const CloseSVG = () => <svg>{/* ... */}</svg>;

const MyComponent = () => <CloseSVG />;

Installation

npm install --save-dev babel-plugin-inline-react-svg

Usage

Via .babelrc (Recommended)

.babelrc

{
  "plugins": [
    "inline-react-svg"
  ]
}

Options


**Note:** If `plugins` field is specified the default enabled `svgo` plugins will be overrided. Alternatively, if your Babel config is in JavaScript, the default list of plugins can be extended by making use of the `extendDefaultPlugins` utility provided by `svgo`.

```js
const { extendDefaultPlugins } = require('svgo');

module.exports = {
  plugins: [
    [
      'inline-react-svg',
      {
        svgo: {
          plugins: extendDefaultPlugins([
            {
              name: 'removeAttrs',
              params: { attrs: '(data-name)' }
            },
            'cleanupIDs',
          ])
        }
      }
    ]
  ]
}

Via CLI

$ babel --plugins inline-react-svg script.js

Via Node API

require('@babel/core').transform('code', {
  plugins: [
    ['inline-react-svg', { filename: 'filename representing the code' }],
  ]
}) // => { code, map, ast };

Inspired by and code foundation provided by react-svg-loader.