【问题标题】:next.js image is missing src propertynext.js 图像缺少 src 属性
【发布时间】:2022-01-04 20:38:24
【问题描述】:

我收到此错误:

错误:图像缺少 src 属性。

我不确定出了什么问题,因为它可以与我的代码一起使用。在我关闭 vscode 并再次打开它之后,错误发生了。这是我的代码:

navbar.js

import React from "react";
import Link from "next/link";
import Image from "next/image";
import Logo from "../components/svg_logo.svg";

export default function Navbar() {
  return (
    <nav className="bg-transparent">
      <div className="max-w-6xl mx-auto px-4 pt-1.5">
        <div className="flex justify-between">
          <div className="flex space-x-4">
            <div>
              <Link href="#">
                <a className="flex items-center py-5 px-2 select-none text-gray-700 text-2xl hover:text-gray-900">
                  <Image src={Logo} alt="logo" height={30} width={30} />
                  <span className="font-bold text-white">Logo</span>
                </a>
              </Link>
            </div>
          </div>
        </div>
      </div>
    </nav>
  );
}

next-config.js

module.exports = {
  reactStrictMode: true,

  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/,
      use: ["@svgr/webpack"]
    });

    return config;
  }
}

【问题讨论】:

  • 我认为不需要优化 SVG 图像。如果您需要完成此操作,请将 Image svg 资产放在公共文件夹中

标签: reactjs svg next.js tailwind-css next-images


【解决方案1】:

我从next.config.js 中删除了不必要的设置webpack config。您可以通过两种方式显示您的徽标 svg,直接来自Image src 或来自@987654330 的import @,两者都可以正常工作,如下所示:

example.js

import Link from "next/link";
import Image from "next/image";
import Logo from "../public/images/nextjs.svg";

function ExamplePage() {
  return (
    <nav className="bg-green-600">
      <div className="max-w-6xl mx-auto px-4 pt-1.5">
        <div className="flex justify-between">
          <div className="flex space-x-4">
            <div>
              <Link href="#">
                <a className="flex items-center py-5 px-2 select-none text-gray-700 text-2xl hover:text-gray-900">
                  <Image
                    // src="/images/nextjs.svg"
                    src={Logo}
                    alt="logo"
                    height={60}
                    width={60}
                  />
                  <span className="font-bold text-white">Logo</span>
                </a>
              </Link>
            </div>
          </div>
        </div>
      </div>
    </nav>
  );
}

export default ExamplePage;

next.config.js 我删除了webpack(config)

module.exports = {
  reactStrictMode: true,
};

项目文件夹和文件结构:


输出:

用 "next": "12.0.7","re​​act": "17.0.2","tailwindcss": "^3.0.5" 测试

【讨论】:

  • 再次感谢您!你是一个真正的救生员!
  • @QI10 快乐都是我的!不客气 ;-) 最好的问候!
猜你喜欢
  • 1970-01-01
  • 2021-03-27
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
相关资源
最近更新 更多