简体   繁体   English

Nextjs:无法从 static 文件夹加载图像

[英]Nextjs: Unable to load images from static folder

How can I load images in a component in Next.js?如何在 Next.js 的组件中加载图像? Do I have to build the project first?我必须先构建项目吗? If yes, is there a way to load the images without building first?如果是,有没有一种方法可以在不先构建的情况下加载图像? I cannot get this to work, no matter what I try.无论我尝试什么,我都无法让它工作。

from the docs: 从文档:

Next.js can serve static files, like images, under a folder called public in the root directory. Next.js 可以在根目录中名为 public 的文件夹下提供静态文件,如图像。 Files inside public can then be referenced by your code starting from the base URL (/).然后,您的代码可以从基本 URL (/) 开始引用 public 中的文件。

So, first add an image to public/my-image.png and then you can reference it:因此,首先将图像添加到public/my-image.png ,然后您可以引用它:

<img src="/my-image.png" />

I think next.js will have a watch on this directory so you won't need to re start your server every time you put something in there.我认为 next.js 会对这个目录有一个监视,所以你每次在那里放东西时都不需要重新start你的服务器。

Another way I find out Next Images我找到下一张图片的另一种方式

installation : npm install --save next-images安装npm install --save next-images

or yarn add next-imagesyarn add next-images

Usage :用法

Create a next.config.js in your project在你的项目中创建一个next.config.js

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

Optionally you can add your custom Next.js configuration as parameter您可以选择将自定义 Next.js 配置添加为参数

// next.config.js
const withImages = require('next-images')
module.exports = withImages({
  webpack(config, options) {
    return config
  }
})

And in your components or pages simply import your images:在您的组件或页面中,只需导入您的图像:

export default () => <div>
  <img src={require('./my-image.jpg')} />
</div>

or要么

import myImg from './my-image.jpg'

export default () => <div>
  <img src={myImg} />
</div>

The static directory has been deprecated.静态目录已被弃用。 Place files in public/static directory将文件放在public/static目录中

With Next 10+ To serve an optimized image:使用 Next 10+ 要提供优化的图像:

import Image from 'next/image'
<Image src={'banner.jpg'} alt='Home Page' width={100} height={100} />

Place the image in the public folder.将图像放在公用文件夹中。 All the referenced images must be present in the public folder at the build time.在构建时,所有引用的图像必须存在于公共文件夹中。 Image hot deployment will not work for images that reside in the public folder.映像热部署不适用于位于公用文件夹中的映像。 You also can refer to cross-domain images with <Image> tag.您还可以使用<Image>标签引用跨域图像。

<Image src={'https://www.example.com/banner.jpg'} alt='Home Page' width={100} height={100} />

To allow cross-domain images, ensure to add the below entry to your next.config.js要允许跨域图像,请确保将以下条目添加到next.config.js

module.exports = {
images: {
    domains: ['www.example.com'],
},

} }

what i like to do for directing to images is using environment variables .我喜欢做的定向图像是使用environment variables in next.js they are easily set in next.config.js file like below:在 next.js 中,它们很容易在next.config.js文件中设置,如下所示:

// next.config.js

module.exports = {
    env: {
      PUBLIC_URL: '/',
    }
};

then you can direct to your publics path wherever it is by using process.env.PUBLIC_URL like below:然后您可以使用如下所示的process.env.PUBLIC_URL直接访问您的公共路径:

<img src={`${process.env.PUBLIC_URL}/my-image.jpg`} />

the advantages of using PUBLIC_URL environment variable over hard coding the path is that you can use another path for when file arrangements change (like in server).使用 PUBLIC_URL 环境变量而不是硬编码路径的优点是,当文件排列发生变化时(如在服务器中),您可以使用另一个路径。 for then you could set conditionally which PUBLIC_URL value to use in production and development.然后你可以有条件地设置在生产和开发中使用哪个 PUBLIC_URL 值。

From Next.js v11 onwards, one can now directly import images without any additional config or dependencies.从 Next.js v11 开始,现在可以直接import图像而无需任何额外的配置或依赖项。 Official example (comment mine):官方示例(评论我的):

import Image from 'next/image'
import profilePic from '../public/me.png'

function Home() {
  return (
    <>
      <h1>My Homepage</h1>
      <Image src={profilePic} alt="Picture of the author" />
      {/* <img src={profilePic.src} alt="Picture of the author" /> */}
      <p>Welcome to my homepage!</p>
    </>
  )
}

export default Home

Docs: next/image文档: next/image

You can load an image in Next.js in many ways.您可以通过多种方式在 Next.js 中加载图像。

#1. #1. Local Images本地图片

Assumed, you have one image on your public directory with the name is your_image_name.jpg假设您的public目录中有一张图片,名称为your_image_name.jpg

You can render an image using following this code.您可以使用以下代码渲染图像。

import Image from 'next/image'
import YourImage from '../public/your_image_name.jpg'

export default function AppLayout(){
  return (
    <>
        <h2>Hello World</h2>
        <Image
            src={YourImage}
            alt="Awesome image"
            ...
        />
    </>
  )
}

#2. #2. Remote Images远程图像

You will use an external image, like your public website directory or third-party website.您将使用外部图像,例如您的公共网站目录或第三方网站。

import Image from 'next/image'

export default function AppLayout() {
  return (
    <>
      <h2>Hello World</h2>
      <Image
        src="https://images.pexels.com/photos/792199/pexels-photo-792199.jpeg?crop=entropy&cs=srgb&dl=pexels-nao-triponez-792199.jpg&fit=crop&fm=jpg&h=427&w=640"
        alt="Awesome Images"
        width={500}
        height={500}
        ...
      />
    </>
  )
}

Don't forget to create a new file next.config.js in the main directory.不要忘记在主目录中创建一个新文件next.config.js In the example, you follow configuration.在示例中,您遵循配置。

module.exports = {
  images: {
    domains: ['images.pexels.com'],
  },
}

It works for me.这个对我有用。

For many options, you can read the Next.js docs .对于许多选项,您可以阅读Next.js 文档

Thanks :)谢谢 :)

I will add here one obvious case, that is usually easily forgotten.我将在这里添加一个明显的案例,它通常很容易被遗忘。 It keeps appearing when one re-structure a site page and our IDE "silently fails" to update the paths of a related file/component or simply when one is more tired or distracted.当重新构建站点页面并且我们的 IDE “静默失败”以更新相关文件/组件的路径时,或者只是当一个人更加疲倦或分心时,它会不断出现。

If you are using a page inside a folder ex: mysiteDomain/pagefolder/page You should be careful when using relative path.如果您正在使用文件夹内的页面,例如: mysiteDomain/pagefolder/page您在使用相对路径时应该小心。 Something like <img src="logo.png" /> should be changed it to <img src="../logo.png" /> since the compiled page will also be inside a folder pagefolder . <img src="logo.png" />之类的东西应该改成<img src="../logo.png" />因为编译后的页面也将在一个文件夹pagefolder中。 The path in the src attribute will be relative to the compiled page. src属性中的路径将相对于编译页面。

As an alternative, you could simply use an absolute path like for ex <img src="/logo.png" /> .作为替代方案,您可以简单地使用绝对路径,例如 ex <img src="/logo.png" /> The path in the src attribute will be relative to the compiled root of the site. src属性中的路径将相对于站点的编译根目录。

Do NOT put public into /src !不要将public放入/src

In my case, I had a src dir into which I put my pages etc., which is an option described here .就我而言,我有一个src目录,我将pages等放入其中,这是此处描述的一个选项。 But I ALSO accidentally moved the public dir there.但我也意外地将public目录移到了那里。 This will mess nextjs up -- you need to keep public in the root dir.这会使 nextjs 变得混乱——您需要在根目录中public

After running next build && next export and your images are not visible do this:在运行next build && next export并且您的图像不可见后,请执行以下操作:

// next.config.js
/** @type {import('next').NextConfig} */

module.exports = {
  reactStrictMode: true,

  images: {
    loader: "custom",
    loaderFile: "./imageLoader.js",
  },

  assetPrefix: "./",

  env: {
    // dev does not need static path
    ROOTDIR: process.env.NODE_ENV === "development" ? "" : "file:///C:/Users/.../out",
  },
};

Create an imageLoader.js too in the root project在根项目中也创建一个 imageLoader.js

export default function imageLoader({ src, width, quality }) {
  return `process.env.NODE_ENV === "development" ? "" : "file:///C:/Users/.../out${src}?w=${width}?q=${quality || 75}`;
}

Where file:///C:/Users/.../out refers to full path to the root of your build其中file:///C:/Users/.../out指的是构建根目录的完整路径

Now you can append process.env.ROOT before "/*"现在你可以在“/*”之前的 append process.env.ROOT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM