Nextjs: Unable to load images from static folder

為{幸葍}努か 提交于 2020-02-29 22:02:50

问题


How can I load images in a component in 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.


回答1:


from the docs:

Just place your files in static directory then you can reference them in your app like:

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

I think next.js will have a watch on this directory so I don't think you need to restart your server every time you put something in there.

But of course when your production build will get updated. You need to build it every time you change something in your app.




回答2:


The static directory has been deprecated. Place files in public/static directory




回答3:


Another way I find out Next Images

installation: npm install --save next-images

or yarn add next-images

Usage:

Create a next.config.js in your project

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

Optionally you can add your custom Next.js configuration as parameter

// 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>


来源:https://stackoverflow.com/questions/49435368/nextjs-unable-to-load-images-from-static-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!