0

我看到能够使用公共文件夹以外的其他目录使用图像的另一种方法是使用 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,
});

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

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

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

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

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

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

4

1 回答 1

6

在你的tsconfig.json,添加next-env.d.tsexclude数组:

{
  // ...
  "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您的用例根本不需要 using。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"/>

参考:图像导入

于 2021-07-26T16:30:26.900 回答