next.js 프로젝트 진행 중 svg 파일을 import해 사용하려고 하자
Error: Element type is invalid:
expected a string (for built-in components) or a
class/function (for composite components) but got: object.
이런 에러가 떴다.
React에서는 그냥 Reactcomponent로 import 하면 아무런 문제가 없었는데, 갑자기 에러가 떠서 당황했다. 찾아보니 svgr webpack을 다운로드 받아야한다는 것을 알았다.
npm i -D @svgr/webpack
next.config.js or. mjs 내부에
/** @type {import('next').NextConfig} */
const nextConfig = {
webpack: (config) => {
config.module.rules.push({
test: /\.svg$/i,
use: ["@svgr/webpack"],
});
return config;
},
};
module.exports = nextConfig;
이렇게 작성해주면된다.
나는 next.config.mjs 에 이미 styled-components compiler 설정을 해두었기 때문에 아래에 추가하여
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
compiler: {
styledComponents: true,
},
webpack: (config) => {
config.module.rules.push({
test: /\.svg$/,
use: ['@svgr/webpack'],
});
return config;
},
};
export default nextConfig;
이렇게 작성했다 !
나는 public/svg 의 파일들을 한번에 모아두는 index.tsx 파일을 생성해두어 import 해오기 쉽게 구조를 만들었다.
//public/svgindex.tsx
import DownArrow from './bottom_arrow.svg';
export { DownArrow };
filter 쓰는 곳 ->
import { DownArrow } from '../../../public/svg/index';
...
<DownArrow />
이렇게 적용하면 짜잔.