LoginSignup
7
4

More than 5 years have passed since last update.

ReactでSVGを読み込んでdata:で埋め込む

Last updated at Posted at 2017-05-17

いくつかローダーあったけど、これが素直でした。

npm i svg-url-loader -D

でWebpackの設定は

const path = require('path');

module.exports = {
    entry: {
        console: './src/console/index.js'
    },
    output: {
        filename: './static/dist/[name]/a.js'
    },
    module: {
        rules: [
        {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['env','es2015', 'react']
                }
            }
        },
        {
            test: /\.svg$/,
            use: {
                loader: 'svg-url-loader',
                options: {
                    noquotes: true
                }
            }
        }
        ]
    }
}

※上記はこの記述だけではない。「test: /.svg$/」あたりのオブジェクトが該当箇所です。

ポイントはオプションにnoquotestrueで渡すこと。
最初なにもつけずにやったらみたいにダブルクォーテーションがかぶった。

SVGの読み込みはとくに特別なことせず

import Logo from '../assets/svg/logo.svg';

こういう感じでimportすればOKです。

書きながら「React v15.0」からSVGの云々がサポートされるように云々というのを目にしてしまったけど、
Webpackの設定が悪かったのかコンパイル通らなかったから見なかったことにしよう。

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4