Mos*_*she 9 javascript reactjs webpack next.js nextjs-image
我有一个@svgr/webpack安装了该库的 Next.js 站点。我已配置next.config.js为可以使用@svgr/webpack,现在想要导入 svg 图像并将其与新next/image组件一起使用。
以下是我设置next.config.js文件的方法:
module.exports = {
images: {
domains: ["images.vexels.com"],
},
webpack(config) {
config.module.rules.push({
test: /\.svg$/,
use: ["@svgr/webpack"],
});
return config;
},
};
Run Code Online (Sandbox Code Playgroud)
这就是我想做的:
import Image from 'next/image'
import Logo from '@/svg/logo.svg'
<Image src={Logo} width={174} height={84} />
Run Code Online (Sandbox Code Playgroud)
但是,当我这样做时,我收到以下错误:
Unhandled Runtime Error
TypeError: src.startsWith is not a function
Source
client\image.tsx (278:13) @ Image
276 | let isLazy =
277 | !priority && (loading === 'lazy' || typeof loading === 'undefined')
> 278 | if (src && src.startsWith('data:')) {
| ^
279 | // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
280 | unoptimized = true
281 | isLazy = false
Run Code Online (Sandbox Code Playgroud)
我想也许我应该将 Logo 组件作为实际组件包含在内,如下所示:<Image src={<Logo />} width={174} height={84} />
然而,这也不起作用。
知道出了什么问题以及如何解决吗?
使用当前的 webpack 配置导入@/svg/logo.svg只会将 SVG 文件作为 React 组件导入。
要将其作为数据 URL 导入,您需要在next.config.js.
module.exports = {
images: {
domains: ['images.vexels.com']
},
webpack(config) {
config.module.rules.push({
test: /\.svg$/,
use: ['@svgr/webpack', 'url-loader']
});
return config;
}
};
Run Code Online (Sandbox Code Playgroud)
然后您就可以以两种方式使用它:作为 URL 或作为组件。
import Image from 'next/image'
import svgUrl, { ReactComponent as Logo } from '@/svg/logo.svg'
<Image src={svgUrl} width={174} height={84} />
// or as a component
<Logo />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7503 次 |
| 最近记录: |