SVG를 Next.js로 가져올 수 없습니다.
SVG 이미지를 Import하려고 하면 다음 오류가 나타납니다.SVG 이미지를 가져오려면 어떤 로더를 사용해야 합니까?
./static/Rolling-1s-200px.svg 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 2000"><filter id="b"><feGaussianBlur stdDeviation="12" /></filter><path fill="#817c70" d="M0 0h2000v2000H0z"/><g filter="url(#b)" transform="translate(4 4) scale(7.8125)" fill-opacity=".5"><ellipse fill="#000210" rx="1" ry="1" transform="matrix(50.41098 -3.7951 11.14787 148.07886 107 194.6)"/><ellipse fill="#eee3bb" rx="1" ry="1" transform="matrix(-56.38179 17.684 -24.48514 -78.06584 205 110.1)"/><ellipse fill="#fff4bd" rx="1" ry="1" transform="matrix(35.40604 -5.49219 14.85017 95.73337 16.4 123.6)"/><ellipse fill="#79c7db" cx="21" cy="39" rx="65" ry="65"/><ellipse fill="#0c1320" cx="117" cy="38" rx="34" ry="47"/><ellipse fill="#5cb0cd" rx="1" ry="1" transform="matrix(-39.46201 77.24476 -54.56092 -27.87353 219.2 7.9)"/><path fill="#e57339" d="M271 159l-123-16 43 128z"/><ellipse fill="#47332f" cx="214" cy="237" rx="242" ry="19"/></g></svg>
SVG Import를 처리할 웹 팩로더를 제공해야 합니다.유명한 로더 중 하나가 svgr입니다.
다음에서 동작하도록 설정하려면 , 다음의 에 를 추가할 필요가 있습니다.next.config.js
다음과 같이 로더의 사용 상황을 기록합니다.
// next.config.js
module.exports = {
webpack(config) {
config.module.rules.push({
test: /\.svg$/,
issuer: {
test: /\.(js|ts)x?$/,
// for webpack 5 use
// { and: [/\.(js|ts)x?$/] }
},
use: ['@svgr/webpack'],
});
return config;
},
};
설정의 상세한 것에 대하여는, 문서를 참조해 주세요.
먼저 설치하는 것을 잊지 마십시오.
$ npm install --save-dev @svgr/webpack
편집
를 추가했습니다.issuer
이러한 svg를 컴포넌트로서 엄밀하게 하는 섹션은 Import된 svg의 경우뿐입니다.js / ts
파일입니다.이것에 의해, 다른 동작을 설정할 수 있습니다.svg
다른 파일 형식(예:.css
)
빠른 방법:<img>
또는<Image>
인터랙티브 SVG에 적합하지 않거나 외부 CSS/J에 의해 SVG를 조작하려는 경우
공식 컴포넌트를 사용할 수 있습니다.img
태그(이 답변에서 설명한 바와 같이)를 지정합니다.
그냥 네 옷만 움직이면 돼svg
대신 파일링하다static
다음과 같은 작업을 수행합니다.
import Image from 'next/image';
// ...
<Image src="/Rolling-1s-200px.svg" width="2000" height="2000" />
하지만 이 방법을 사용함으로써svg
파일은 응답에 직접 표시되지 않고 브라우저에 태그가 붙습니다.
또, 특정할 필요가 있습니다.width
그리고.height
단, Atribute에서 계산할 수 있습니다.
Next.js v11 이상에서는 다음 작업도 수행할 수 있습니다.
import Image from 'next/image';
import Illustration from '../static/Rolling-1s-200px.svg';
// ...
<Image src={Illustration} />
// one needs to use `Illustration.src` to get the source URL
// <img src={Illustration.src} ... />
HTML에 SVG 포함(Webpack-5, TS용)
승인된 답변은 이 작업을 수행하는 방법을 보여 줍니다.webpack-4
단, 그 이후로는webpack-5
디폴트 설정입니다.해당 설정을 공유합니다.인스톨 후에 사용할 수 있습니다(yarn add -D @svgr/webpack
또는npm install @svgr/webpack --save-dev
):
// next.config.js
// https://github.com/gregberge/svgr/issues/551#issuecomment-839772396
module.exports = {
// other configs...
// future: { webpack5: true }, // -- not needed since Next.js v11.0.0
webpack(config) {
config.module.rules.push({
test: /\.svg$/i,
issuer: { and: [/\.(js|ts|md)x?$/] },
use: [
{
loader: '@svgr/webpack',
options: {
prettier: false,
svgo: true,
svgoConfig: { plugins: [{ removeViewBox: false }] },
titleProp: true,
},
},
],
});
return config;
},
};
사용하지 않는 경우options
로더의 경우는, 간단하게 다음과 같이 기술할 수 있습니다.
use: ['@svgr/webpack']
v6를 사용하는 경우@svgr/webpack
다음에, 다음과 같이 SVGO 설정을 지정할 필요가 있습니다.
// ...
plugins: [
{
name: 'preset-default',
params: {
overrides: { removeViewBox: false },
},
},
],
// ...
타이프스크립트를 사용하는 경우 Import처 디렉토리에서 적절한 모듈을 정의해야 합니다.svg
또는 루트에 다음과 같이 추가합니다.<some-name>.d.ts
포함시키다tsconfig
):
// index.d.ts
declare module '*.svg' {
const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
export default ReactComponent;
}
그런 다음 다음과 같이 사용할 수 있습니다.
import Illustration from '../static/Rolling-1s-200px.svg';
// ...
<Illustration />
주의: Next.js v11.0.1+는 SVG를 내보내기 모듈로 선언했습니다.any
커스텀 설정에 의해, 다음에 의해 설정된 타입은 덮어쓰지 않습니다.next-env.d.ts
후자를 제외하지 않는 한.이것을 참고해 주세요.
[구식(고정)] 갱신:
Next.js v11.0.0을 사용하는 경우 SVG를 가져오는 동안 오류가 발생할 수 있습니다.갱신해 주세요v11.0.1
또는 그 이상입니다.이 코멘트에 기재되어 있는 회피책을 따라 주세요.
다음 이미지를 설치합니다.
yarn add -D next-images
프로젝트에서 next.config.js를 만듭니다.
// next.config.js
const withImages = require('next-images')
module.exports = withImages()
개인적으로 SVG 이미지를 React 컴포넌트로 취급하여 Create React App과 마찬가지로 자동으로 인라인화할 수 있는 next-react-svg 플러그인을 선호합니다.
사용 방법은 다음과 같습니다.
next-react-svg
:
npm i next-react-svg
- 「」에 을 추가합니다.
next.config.js
:
const withReactSvg = require('next-react-svg')
const path = require('path')
module.exports = withReactSvg({
include: path.resolve(__dirname, 'src/assets/svg'),
webpack(config, options) {
return config
}
})
매개 변수는 필수이며 SVG 이미지 폴더를 가리킵니다.
Next.js에 대해 이미 사용하도록 설정된 플러그인이 있는 경우 next-compose-plugins를 사용하여 올바르게 결합하는 것을 고려해 보십시오.
- SVG를 일반 React 구성 요소로 가져옵니다.
import Logo from 'assets/svg/Logo.svg';
export default () => (
<Logo />
);
바로 그겁니다.앞으로 Next.js는 이와 같이 Import된 SVG 이미지를 SVG 태그로 렌더링된 마크업에 포함시킵니다.
babel-plugin-inline-react-svg를 사용할 수 있습니다.
import React from 'react';
import CloseSVG from './close.svg';
const MyComponent = () => <CloseSVG />;
npm install --save-dev babel-plugin-inline-react-svg
// .babelrc
{
"plugins": [
"inline-react-svg"
]
}
자세한 내용은 링크를 참조하십시오.
이것은 다른 의존관계 없이 나에게 효과가 있었다.
// In next.config.js
module.exports = {
webpack (config, options) {
config.module.rules.push({
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000
}
}
});
return config;
}
};
는 Import를 통해 할 수 .<img>
붙이다
<img src='./next.svg' alt='next' />
svg가 공용 폴더에 있는지 확인합니다.
★★★★★★★★★★★★★★★★ Next.js 12.0.9
★★★★★★★★★★★★★★★★★」Webpack 5
이거면 돼요.
yarn add --dev url-loader @svgr/webpack
// next.config.js
module.exports = {
webpack(config, options) {
config.module.rules.push({
test: /\.svg$/,
use: ['@svgr/webpack', 'url-loader'],
});
return config;
},
};
SVG를 Next.js 컴포넌트로 Import하는 방법
라이브러리를 설치하지 않은 다른 솔루션
import React from "react";
export default function GoogleLogo() {
return (
<svg className="svgIcon-use" width="25" height="37" viewBox="0 0 25 25">
<g fill="none" fillRule="evenodd">
<path
d="M20.66 12.693c0-.603-.054-1.182-.155-1.738H12.5v3.287h4.575a3.91 3.91 0 0 1-1.697 2.566v2.133h2.747c1.608-1.48 2.535-3.65 2.535-6.24z"
fill="#4285F4"
/>
<path
d="M12.5 21c2.295 0 4.22-.76 5.625-2.06l-2.747-2.132c-.76.51-1.734.81-2.878.81-2.214 0-4.088-1.494-4.756-3.503h-2.84v2.202A8.498 8.498 0 0 0 12.5 21z"
fill="#34A853"
/>
<path
d="M7.744 14.115c-.17-.51-.267-1.055-.267-1.615s.097-1.105.267-1.615V8.683h-2.84A8.488 8.488 0 0 0 4 12.5c0 1.372.328 2.67.904 3.817l2.84-2.202z"
fill="#FBBC05"
/>
<path
d="M12.5 7.38c1.248 0 2.368.43 3.25 1.272l2.437-2.438C16.715 4.842 14.79 4 12.5 4a8.497 8.497 0 0 0-7.596 4.683l2.84 2.202c.668-2.01 2.542-3.504 4.756-3.504z"
fill="#EA4335"
/>
</g>
</svg>
);
}
및 용도:
import GoogleLogo from "./GoogleLogo";
class Login extends React.Component {
render() {
return (
<LoginLayout title="Login Page">
<div>
<Link href="/auth/google">
<a className="button">
<div>
<span className="svgIcon t-popup-svg">
<GoogleLogo />
</span>
</div>
</a>
</Link>
</div>
</LoginLayout>
);
}
}
어떤 구성이나 종속성을 설치하지 않고 코드에서 SVG 파일을 사용하고 태그의 속성을 완전히 제어하려면 SVG 파일을 JSX 또는 TSX 구성 요소로 변환하는 것이 가장 좋습니다.
JSX 솔루션:
export const YourSVg = ({color, width, height}) => (
<svg fill={color} height={height} width={width}>
..rest of the svg tags...
</svg>
)
TSX 솔루션:
export const YourSVg:React.FC<{color:string, width:string, height:string}> =
({color, width, height}) => (
<svg color={color} height={height} width={width}>
..rest of the svg tags...
</svg>
)
사용방법?
일반 컴포넌트처럼 Import하여 이전과 동일하게 사용할 수 있습니다.
예를 들어 다음과 같습니다.
import YourSVg from '../from the path/path
<YourSVg color='red' width='10px' height='10px/>
첫 번째 답변을 시도했지만 오류가 발생했기 때문에 다음과 같이 됩니다.
module.exports = {
webpack(config) {
config.module.rules.push({
test: /\.svg$/,
use: ["@svgr/webpack"]
});
return config;
}};
하시면 됩니다.next-plugin-svgr
&next-compose-plugins
플러그인을 청소하려면(있는 경우):
// next.config.js
const withPlugins = require("next-compose-plugins");
const withSvgr = require("next-svgr");
module.exports = withPlugins([
withSvgr
// your other plugins here
]);
그냥 '그냥'일 수도 있어요.next-plugin-svgr
:
// next.config.js
const withSvgr = require('next-plugin-svgr');
module.exports = withSvgr({
webpack(config, options) {
return config;
},
});
출처 : https://www.npmjs.com/package/next-plugin-svgr
SVG를 텍스트로 로드하여 삽입하는 가장 간단한 방법 중 하나는 를 사용하는 것입니다.
패키지 「npm」을 합니다.raw-loader
매니저를 ), 그 에 「」를 합니다.
import mySvgContent from "!!raw-loader!../path/to/image.svg";
function MyComponent ()
{
return (
<div dangerouslySetInnerHTML={{__html: mySvgContent}} />
);
}
Nextjs 12 이후를 사용하는 경우 간단한 솔루션이 있습니다.
고객님의 고객명next.config.js
★★★★
module.exports = {
//another configs here
images: {
dangerouslyAllowSVG: true,
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
}
}
나는 여기에 그것을 설립했다.
언급URL : https://stackoverflow.com/questions/55175445/cant-import-svg-into-next-js
'programing' 카테고리의 다른 글
src 변수를 사용한ng-module (0) | 2023.03.28 |
---|---|
MacOS의 VS 코드에서 Python 스크립트를 시작할 때 "SyntaxError: invalid 구문"이 표시됩니다. (0) | 2023.03.28 |
IIS6에서 JSON 파일(POST, GET 등)을 처리하도록 합니까? (0) | 2023.03.23 |
개미 디자인 - 막대한 수입품 (0) | 2023.03.23 |
정의되지 않은 메서드 WP_Textdomain_Registry::reset() 호출 (0) | 2023.03.23 |