【问题标题】:next-images breaking all the absolute paths in my next.js projectnext-images 打破了我的 next.js 项目中的所有绝对路径
【发布时间】:2021-09-17 08:30:18
【问题描述】:

我想在我的 next.js 项目中添加内联 png 图像。由于这不是本机支持的功能,因此我为此使用了 next-images 库。

这是我的next.config.js

const withImages = require('next-images')
module.exports = withImages()

问题不在于图像导入,而是所有其他导入:该代码破坏了我项目中所有绝对的 .jsx 导入。

你知道如何解决这个问题吗?

【问题讨论】:

  • Next.js 中如何配置绝对路径?
  • @juliomalves 我没有任何配置,我只是用import SomeComponent from "/components/SomeComponent" 导入.jsx 文件。他们一直在工作,直到我安装了 next-images
  • @juliomalves 您刚刚发送给我的链接可以回答我的问题。现在可以了

标签: next.js next-images


【解决方案1】:

正如上面提到的用户@juliomalves,答案是来自Next.js 官方文档的on this link

基本上,这个问题分两步解决:

  1. 添加 jsconfig.json 文件(如果您使用的是 Typescript,则应改用 tsconfig.json)。

  2. 将所有绝对路径从/components/Something 更改为components/Something(换句话说,删除第一个正斜杠)。

【讨论】:

    【解决方案2】:

    next/image 的默认行为会将/_next/image?url= 添加到图像src 的任何绝对URL。

    解决方法是使用imgix loader 并将路径设置为''

    // next.config.js
    module.exports = {
      images: {
        domains: ['yourServer.com'],
        path: '',
        loader: 'imgix',
      },
    }
    

    从源代码中,将root = '/_next/image?url=...' 添加到任何绝对URL src 是设计使然: https://github.com/vercel/next.js/blob/f81a6a5f0fc3a33a51112d4d3261d431e704b0da/packages/next/client/image.tsx#L862

    为什么?

    有点奇怪,不同于 HTML <image src=""> 的行为,也让用户感到困惑。

    您可以关注https://github.com/vercel/next.js/issues/19206进行跟进

    【讨论】:

    • OP 没有使用next/image 组件。问题是关于 Next.js 的 next-images 插件。
    猜你喜欢
    • 2011-04-24
    • 2015-04-30
    • 1970-01-01
    • 2022-07-31
    • 1970-01-01
    • 2012-04-06
    • 2011-03-13
    • 2014-12-21
    • 2016-05-08
    相关资源
    最近更新 更多