[Next] svg import 하기

Ell!·2022년 1월 25일
0

next

목록 보기
1/7

next에서 svg import

여러가지 방법이 있는데, 그 중 내가 사용했던 방법은 두가지였다.

Next/Image

첫번째 방법은 next/Image에서 바로 svg를 불러와서 사용하는 방법이다.

<Image
  src={"/logo/github.svg"}
  alt="github"
  width="36px"
  height="36px"
/>

이렇게 하면 손 쉽게 사용할 수 있지만, svg의 color 등을 조절하기 힘들다. 따라서 두 번째 방법을 사용하는 것을 추천한다.

webpack 사용

react에서 사용했던 것처럼 svg를 react component로 import하고 싶을 때 사용하는 방법이다.

조금 복잡하니 사용하는 라이브러리를 쭉 적어놓고 시작하겠다.

"@svgr/webpack": "^6.2.0"
"next": "12.0.7",       

next.config.js

/** @type {import('next').NextConfig} */

const withBundleAnalyzer = require("@next/bundle-analyzer")({
	enabled: process.env.ANALYZE === "true",
});

module.exports = withBundleAnalyzer({
	target: "serverless",
	env: {
		BASE_URL: process.env.BASE_URL,
	},

	webpack(conf) {
		conf.module.rules.push({
			test: /\.svg$/,
			issuer: { and: [/\.(js|ts|md)x?$/] },
			use: [
				{
					loader: "@svgr/webpack",
					options: {
						prettier: false,
						svgo: true,
						titleProp: true,
						svgoConfig: {
							plugins: [
								{
									name: "preset-default",
									params: {
										overrides: { removeViewBox: false },
									},
									// Enable figma's wrong mask-type attribute work
									removeRasterImages: false,
									removeStyleElement: false,
									removeUnknownsAndDefaults: false,
									// Enable svgr's svg to fill the size
									removeViewBox: false,
								},
							],
						},
					},
				},
			],
		});
		// 절대경로
		conf.resolve.modules.push(__dirname);
		return conf;
	},
});

이렇게 넣고 import해보면 아마

Plugin name should be specified
    at Array.map (<anonymous>)

이런 식의 에러가 뜰 것이다. svg파일에서 import할 때, type이 지정되지 않아서 그렇다.

@type/index.d.ts

declare module "*.svg" {
	const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
	export default ReactComponent;
}

tsconfig.json

"include": ["next-env.d.ts", "index.d.ts", "**/*.ts", "**/*.tsx"],

우리가 정의한 d.ts파일도 includes해준다.

// Home.tsx

import GithubIcon from "public/logo/github.svg";

svg를 import하면 react component처럼 쓸 수 있다!

참조

https://stackoverflow.com/questions/55175445/cant-import-svg-into-next-js

profile
더 나은 서비스를 고민하는 프론트엔드 개발자.

0개의 댓글