【问题标题】:How to use PNG images in Next.js outside the default PUBLIC directory?如何在默认 PUBLIC 目录之外的 Next.js 中使用 PNG 图像?
【发布时间】:2021-10-02 14:09:59
【问题描述】:

我看到能够使用公共文件夹以外的其他目录使用图像的另一种方法是使用 Next-Images 库,但是我按照文档中的描述正确地进行了所有设置,我见过几个互联网上的视频,但没有任何效果,我只能加载它的svgs。 我在我的项目中使用打字稿。 我注意到一个关于打字的细节,我们必须添加这个参考:

/// <reference types="next-images" />

变成这样:

/// <reference types="next" />
/// <reference types="next/types/global" />
/// <reference types="next/image-types/global" />
/// <reference types="next-images" />

到 next-env.d.ts 文件,但是每次我运行 yarn dev 命令时,添加的引用都会自动删除。

我的 next.config.js 文件:

const withImages = require('next-images');

module.exports = withImages({
   inlineImageLimit: false,
   esModule:true,
});

我注意到的另一件事是:编译项目时,通过浏览器控制台标记&lt;img src=""&gt;,在src中是路径:

/_next/static/images/cora-c562c6fa203473521a5dc5b15a841192.jpg

由于我通过浏览器控制台手动输入了这条其他路径,因此它可以工作:

/_next/static/image/src/assets/cora.e76cddfc04ca9d4b8a3868b2c40e3b7f.jpg

所以,如果有人知道我是否遗漏了我可能没有完成的任何设置、可能有帮助的视频或文档中的详细信息,我将不胜感激。

下一个版本:11.0.1 打字稿版本:4.3.5 下一张图片版本:1.8.1

【问题讨论】:

    标签: reactjs typescript next.js next-images


    【解决方案1】:

    在您的tsconfig.json 中,将next-env.d.ts 添加到exclude 数组中:

    {
      // ...
      "exclude": ["node_modules", "next-env.d.ts"],
      "include": ["**/*"]
    }
    

    创建一个新文件custom.d.ts 并添加:

    /// <reference types="next" />
    /// <reference types="next/types/global" />
    /// <reference types="next-images" />
    

    在next.config.json:

    const withImages = require('next-images');
    
    module.exports = withImages({
      images: {
        disableStaticImages: true,
      },
    });
    

    请注意,您的用例根本不需要使用next-images。 Next.js 现在支持这个开箱即用。所以使用默认配置(一个新鲜的create-next-app),你可以直接这样做:

    import Image from 'next/image';
    import img from '../path/to/img.png';
    
    <Image src={img} alt="some text"/>
    
    // or with img tag:
    
    <img src={img.src} height="100" width="100" alt="some text"/>
    

    参考:Image Imports

    【讨论】:

    • 非常感谢!完美运行!
    猜你喜欢
    • 2010-09-20
    • 2021-03-29
    • 2018-07-07
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 2013-07-19
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多