react-inlinesvg vs react-svg vs react-svg-inline vs react-svg-loader vs svg-inline-react
SVGのインライン化
react-inlinesvgreact-svgreact-svg-inlinereact-svg-loadersvg-inline-react類似パッケージ:

SVGのインライン化

SVGのインライン化は、ウェブ開発においてSVG(Scalable Vector Graphics)ファイルをHTMLドキュメント内に直接埋め込む手法です。これにより、SVG画像が外部ファイルとして読み込まれるのではなく、HTMLの一部として扱われます。インライン化の利点には、CSSやJavaScriptを使ってSVGのスタイルやアニメーションをより細かく制御できること、HTTPリクエストの数を減らしてページの読み込み速度を向上させること、そしてアクセシビリティやSEOの向上が含まれます。Reactでは、SVGをインライン化するためのさまざまなライブラリが提供されており、これらを活用することで効率的にSVGを扱うことができます。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
react-inlinesvg01,311189 kB09日前MIT
react-svg0881313 kB31ヶ月前MIT
react-svg-inline0222-38年前MIT
react-svg-loader0640-487年前MIT
svg-inline-react0132-165年前MIT

機能比較: react-inlinesvg vs react-svg vs react-svg-inline vs react-svg-loader vs svg-inline-react

インライン化方法

  • react-inlinesvg:

    react-inlinesvgは、外部SVGファイルをURLから読み込み、インライン化します。これにより、SVGファイルを外部に保持しながら、インライン化の利点を享受できます。

  • react-svg:

    react-svgは、SVGファイルをReactコンポーネントとしてインポートし、インライン化します。これにより、SVGをコンポーネントとして扱い、スタイルやイベントを簡単に追加できます。

  • react-svg-inline:

    react-svg-inlineは、SVGコードを直接インライン化します。外部ファイルを使用せずに、SVGコードをコンポーネント内に埋め込むことができます。

  • react-svg-loader:

    react-svg-loaderは、Webpackのビルドプロセス中にSVGファイルをReactコンポーネントに変換します。これにより、ビルド時にSVGがコンポーネント化され、効率的なインライン化が可能になります。

  • svg-inline-react:

    svg-inline-reactは、SVGコードをインライン化してReactコンポーネントとして表示します。シンプルで軽量なインライン化が特徴です。

カスタマイズ性

  • react-inlinesvg:

    react-inlinesvgは、インライン化されたSVGに対してカスタムクラスやスタイルを適用できます。また、SVGの読み込み中やエラー時のハンドラを設定することも可能です。

  • react-svg:

    react-svgは、SVGコンポーネントに対してスタイルやクラスを自由に設定できます。また、SVG内の要素に対してもスタイルを適用することができます。

  • react-svg-inline:

    react-svg-inlineは、インライン化されたSVGに対してカスタムクラスやスタイルを適用できますが、機能は比較的シンプルです。

  • react-svg-loader:

    react-svg-loaderは、Webpackの設定を通じてカスタマイズ可能です。SVGの最適化や属性の設定など、ビルドプロセス中にさまざまなカスタマイズが可能です。

  • svg-inline-react:

    svg-inline-reactは、シンプルなインライン化を提供しますが、カスタマイズ性は限られています。

パフォーマンス

  • react-inlinesvg:

    react-inlinesvgは、外部SVGファイルを読み込むための追加HTTPリクエストが発生しますが、一度読み込まれればインライン化されるため、スタイルやアニメーションの制御が容易になります。

  • react-svg:

    react-svgは、SVGをコンポーネントとしてインポートするため、バンドルサイズに影響を与える可能性がありますが、インライン化によりレンダリングパフォーマンスが向上します。

  • react-svg-inline:

    react-svg-inlineは、SVGコードを直接インライン化するため、追加のHTTPリクエストが不要で、パフォーマンスに優れています。

  • react-svg-loader:

    react-svg-loaderは、ビルド時にSVGをコンポーネント化するため、ランタイムのパフォーマンスに影響を与えません。最適化されたSVGを使用することで、レンダリングが効率化されます。

  • svg-inline-react:

    svg-inline-reactは、軽量なインライン化を提供し、追加のHTTPリクエストを回避するため、パフォーマンスに優れています。

Ease of Use: Code Examples

  • react-inlinesvg:

    react-inlinesvgを使用して外部SVGファイルをインライン化する例

    import InlineSVG from 'react-inlinesvg';
    
    const MyComponent = () => (
      <div>
        <InlineSVG src="/path/to/your.svg" />
      </div>
    );
    
  • react-svg:

    react-svgを使用してSVGファイルをReactコンポーネントとしてインポートする例

    import { ReactSVG } from 'react-svg';
    
    const MyComponent = () => (
      <div>
        <ReactSVG src="/path/to/your.svg" />
      </div>
    );
    
  • react-svg-inline:

    react-svg-inlineを使用してSVGコードを直接インライン化する例

    import SVGInline from 'react-svg-inline';
    
    const svgCode = `
      <svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
        <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
      </svg>
    `;
    
    const MyComponent = () => (
      <div>
        <SVGInline svg={svgCode} />
      </div>
    );
    
  • react-svg-loader:

    react-svg-loaderを使用してSVGファイルをReactコンポーネントとしてインポートする例(Webpack設定が必要)

    import MySVG from './my-icon.svg';
    
    const MyComponent = () => (
      <div>
        <MySVG />
      </div>
    );
    
  • svg-inline-react:

    svg-inline-reactを使用してSVGコードをインライン化する例

    import InlineSVG from 'svg-inline-react';
    
    const svgCode = `
      <svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
        <rect width="100" height="100" fill="blue" />
      </svg>
    `;
    
    const MyComponent = () => (
      <div>
        <InlineSVG src={svgCode} />
      </div>
    );
    

選び方: react-inlinesvg vs react-svg vs react-svg-inline vs react-svg-loader vs svg-inline-react

  • react-inlinesvg:

    react-inlinesvgは、外部SVGファイルをインライン化して埋め込むのに適しています。特に、SVGファイルをURLから読み込み、インライン化する必要がある場合に便利です。

  • react-svg:

    react-svgは、SVGファイルをReactコンポーネントとしてインポートし、インライン化することができます。特に、SVGをコンポーネントとして扱いたい場合や、スタイルやイベントを簡単に追加したい場合に適しています。

  • react-svg-inline:

    react-svg-inlineは、SVGコードを直接インライン化するためのシンプルなライブラリです。特に、小さなSVGを直接コンポーネント内に埋め込みたい場合や、外部ファイルを使用せずにSVGをインライン化したい場合に適しています。

  • react-svg-loader:

    react-svg-loaderは、Webpackのローダーとして機能し、SVGファイルをReactコンポーネントに変換します。特に、ビルドプロセス中にSVGをコンポーネント化したい場合や、カスタマイズ可能なローダー設定が必要な場合に適しています。

  • svg-inline-react:

    svg-inline-reactは、SVGコードをインライン化してReactコンポーネントとして表示するシンプルなライブラリです。特に、軽量でシンプルなインライン化が必要な場合や、最小限の設定でSVGをインライン化したい場合に適しています。

react-inlinesvg のREADME

react-inlinesvg

NPM version CI Quality Gate Status Coverage

Load inline, local, or remote SVGs in your React components.

View the demo

Highlights

  • 🏖 Easy to use: Just set the src
  • 🛠 Flexible: Personalize the options to fit your needs
  • ⚡️ Smart: Async requests will be cached.
  • 🚀 SSR: Safe for server-side rendering

Usage

npm i react-inlinesvg

And import it into your code:

import SVG from 'react-inlinesvg';

export default function App() {
  return (
    <main>
      <SVG
        src="https://cdn.svglogos.dev/logos/react.svg"
        width={128}
        height="auto"
        title="React"
      />
    </main>
  );
}

Props

src {string} - required. The SVG to load. It accepts:

  • A URL or path to an SVG file (absolute or relative, including from a bundler import)
  • A data URI (base64 or URL-encoded)
  • A raw SVG string

baseURL {string} A URL to prepend to url() references inside the SVG when using uniquifyIDs. Required if your page uses an HTML <base> tag.

children {ReactNode}
The fallback content in case of a fetch error or unsupported browser.

<SVG src="...">
	<img src="https://raw.githubusercontent.com/gilbarbara/react-inlinesvg/HEAD/..." alt="fallback" />
</SVG>

cacheRequests {boolean} ▶︎ true Cache remote SVGs in memory. When used with the CacheProvider, requests are also persisted in the browser cache.

description {string}
A description for your SVG. It will override an existing <desc> tag.

fetchOptions {RequestInit}
Custom options for the request.

innerRef {React.Ref<SVGElement | null>} Set a ref on the SVG element.

The SVG is processed and parsed so the ref won't be set on the initial render. You can use the onLoad callback to get and use the ref instead.

loader {node}
A component to be shown while the SVG is loading.

onError {function}
A callback to be invoked if loading the SVG fails.
This will receive a single argument with:

  • a FetchError with:
{
  message: string;
  type: string;
  errno: string;
  code: string;
}
  • or an Error for issues like missing src, unsupported browser, or invalid SVG content.

onLoad {function}.
A callback to be invoked upon successful load.
This will receive 2 arguments: the src prop and an isCached boolean

preProcessor {function} A function to pre-process the SVG string before parsing. Receives the SVG string and must return a string.

title {string | null}
A title for your SVG. It will override an existing <title> tag.
If null is passed, the <title> tag will be removed.

uniqueHash {string} ▶︎ a random 8 characters string [A-Za-z0-9]
A string to use with uniquifyIDs.

uniquifyIDs {boolean} ▶︎ false
Create unique IDs for each icon.

Any additional props will be passed down to the SVG element.

Example

<SVG
  baseURL="/home"
  cacheRequests={true}
  description="The React logo"
  loader={<span>Loading...</span>}
  onError={(error) => console.log(error.message)}
  onLoad={(src, isCached) => console.log(src, isCached)}
  preProcessor={(code) => code.replace(/fill=".*?"/g, 'fill="currentColor"')}
  src="https://cdn.svglogos.dev/logos/react.svg"
  title="React"
  uniqueHash="a1f8d1"
  uniquifyIDs={true}
/>

Caching

You can use the browser's cache to store the SVGs permanently.
To set it up, wrap your app with the cache provider:

import { createRoot } from 'react-dom/client';
import CacheProvider from 'react-inlinesvg/provider';
import App from './App';

createRoot(document.getElementById('root')!).render(
  <CacheProvider>
    <App />
  </CacheProvider>
);

The CacheProvider accepts an optional name prop to customize the cache storage name.

Be aware of the limitations of the Cache API.

Browser Support

Any browser that supports inlining SVGs and fetch will work.

If you need to support legacy browsers, include a polyfill for fetch in your app.

CORS

If you are loading remote SVGs, you must ensure they have CORS headers.

Why do you need this package?

One reason SVGs are awesome is that you can style them with CSS. Unfortunately, this is not useful in practice because the style element has to be in the same document. This leaves you with three bad options:

  1. Embed the CSS in the SVG document
    • Can't use your CSS preprocessors (LESS, SASS)
    • Can't target parent elements (button hover, etc.)
    • Makes maintenance difficult
  2. Link to a CSS file in your SVG document
    • Sharing styles with your HTML means duplicating paths across your project, making maintenance a pain
    • Not sharing styles with your HTML means extra HTTP requests (and likely duplicating paths between different SVGs)
    • Still can't target parent elements
    • Your SVG becomes coupled to your external stylesheet, complicating reuse.
  3. Embed the SVG in your HTML
    • Bloats your HTML
    • SVGs can't be cached by browsers between pages.
    • A maintenance nightmare

But there's an alternative that sidesteps these issues: load the SVG with a GET request and then embed it in the document. This is what this component does.

Note

The SVG <use> element can be used to achieve something similar to this component. See this article for more information and this table for browser support and caveats.

Credits

Thanks to @matthewwithanm for creating this component and so kindly transferring it to me. I'll definitely keep up the good work! ❤️