在某些地方,我需要将SVG文件作为组件导入,以便对其进行控制(例如更改样式,更改SVG元素的填充颜色),我使用了SVGR,而在其他地方,我想将SVG文件作为正常图像使用,并从内置的"next/image"模块功能。
我不能使用next/image模块,因为当我像
一样导入它时import FacebookIcon from "public/images/icons/social/facebook.svg";
FacebookIcon是一个组件
不是next/image组件的src属性可以接受的格式。
从我的理解是src接受string或object
{ src: "**", width: **px, height: **px }
期望用途
import MySVG from "./mySVG.svg?svgr"; // SVGR loader
<MySVG />
import Image from "next/image";
import mySVG from "./mySVG.svg"; // Default NextJS loader
<Image src={mySVG} alt="" /> // (width and height will be applied automatically)
所需next.config.jswebpack(config, { dev: isDev, isServer }) {
config.module.rules.push({
test: /.svg$/i,
issuer: /.[jt]sx?$/,
resourceQuery: /svgr/, // only use svgr to load svg if path ends with *.svg?svgr
use: ["@svgr/webpack"],
});
// Re-add default nextjs loader for svg
config.module.rules.push({
test: /.svg$/i,
loader: "next-image-loader",
issuer: { not: /.(css|scss|sass)$/ },
dependency: { not: ["url"] },
resourceQuery: { not: [/svgr/] }, // Ignore this rule if the path ends with *.svg?svgr
options: { isServer, isDev, basePath: "", assetPrefix: "" },
});
}
需要的typescript声明(如果使用ts)
declare module "*.svg?svgr";
我是怎么想出来的
- 阅读这些文档:https://react-svgr.com/docs/webpack/
- 使用这个代码片段获取应用于svgs的默认规则
webpack(config) {
const defaultSvgLoader = config.module.rules.find(
(rule) => typeof rule?.test?.test === "function" && rule.test.test(".svg")
);
console.log(defaultSvgLoader);
}
- 将
resourceQuery: { not: [/svgr/] }
添加到日志输出对象中,以便*.svg?svgr
路径将被忽略