webpack에서 build 과정에서 svg 파일을 처리할 loader가 필요하다는 내용의 에러가 발생했다.
ERROR in ./lawand-frontend/public/images/icon-google.svg 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
|     <g fill="none" fill-rule="evenodd">
|         <g>
$ yarn add @svgr/webpack -D
svgr을 devDependency로 설치하고 webpack.config.js에 다음과 같이 작성한다.
// webpack.config.js
const webpack = require('webpack');
module.exports = {
  entry: './src/index.js',
  module: {
    rules: [
      //...
      {
        test: /\.svg$/,
        use: ['@svgr/webpack'],
      },
    ],
  },
  //...
};
세팅을 완료하면 기존 2번 해결 방법처럼 { ReactComponent as SvgIcon }로 import할 필요없이 바로 SvgIcon로 사용할 수 있다.
import React from 'react';
import SvgIcon from 'assets/icon.svg';
const App = () =>{
  return(
      <div className='App'>
        <SvgIcon />
      </div>
    );
}
export default App;
나 같은 경우는 Server Side Rendering을 위해 Express에서 React app을 동적으로 호출하다 보니 babel에서 svg 파일을 transpile하지 못하는 에러도 발생했다.
/home/havebeen/lawand/lawand-frontend/public/images/icon-google.svg:1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
^
SyntaxError: Unexpected token '<'
bable이 svg를 읽고 변역할 수 있도록 플러그인을 설치해줬다.
검색을 통해 babel-plugin-inline-svg와 babel-plugin-inline-react-svg를 찾을 수 있었는데, react component로 번역하는 것이 목적이므로 후자를 선택했다.
$ yarn add --D babel-plugin-inline-react-svg
babel-plugin-inline-react-svg을 devDependency로 설치하고 babel.config.js에 플러그인을 등록해줬다.
{
  "plugins": [
    "inline-react-svg"
  ]
}
문서에서는 babelrc를 사용하기를 추천했지만 굳이 지역 설정으로 분리할 필요성을 느끼지 못했다.