面试题答案
一键面试-
安装依赖:
- Next.js 本身对 SVG 的支持有限,通常需要安装
@svgr/webpack
和@next - svg
等相关依赖来更好地处理 SVG。可以使用 npm 或 yarn 安装:
npm install @svgr/webpack @next - svg
或
yarn add @svgr/webpack @next - svg
- Next.js 本身对 SVG 的支持有限,通常需要安装
-
配置 Next.js:
- 在项目根目录创建或编辑
next.config.js
文件。添加如下配置:
const withSvg = require('@next - svg'); module.exports = withSvg({ webpack(config, options) { return config; } });
- 在项目根目录创建或编辑
-
代码实现:
- 假设你的 SVG 文件名为
icon.svg
且位于public
目录下。在页面组件中引入并展示:
import Image from 'next/image'; const MyPage = () => { return ( <div> <Image src="/icon.svg" alt="My SVG Icon" width={50} height={50} /> </div> ); }; export default MyPage;
- 另一种方式,如果使用
@svgr/webpack
,可以将 SVG 作为 React 组件导入。假设 SVG 文件位于components/icons
目录下,首先确保文件路径正确。然后在组件中导入:
import React from'react'; import Icon from '../components/icons/icon.svg'; const MyPage = () => { return ( <div> <Icon /> </div> ); }; export default MyPage;
这里导入的
Icon
就是一个 React 组件,会直接渲染 SVG 内容。根据实际需求可以对 SVG 进行样式调整等操作。 - 假设你的 SVG 文件名为