next-optimized-images icon indicating copy to clipboard operation
next-optimized-images copied to clipboard

Error: Cannot find module in build process

Open AldoS opened this issue 3 years ago • 4 comments

Hi guys, I have an issue with the build process. What I am trying to do, is to save some images from API to my project. I am using the file stream in the getStaticProps function to achieve that.

Then in my page, I require the image that is saved previously: <img src={require('../../../public/images/hero/my-image.jpg?webp')} />

In my first build, I get the error: Error: Cannot find module './my-image.jpg' If I build again everything works fine because the image is already there.

I tried to check if the image exists before the return in getStaticProps using fs.existsSync(file) and my file exists.

Any ideas on the above error or any hints? Thanks

AldoS avatar Sep 08 '20 12:09 AldoS

Same with me, can't build svg sprite

oknoorap avatar Sep 16 '20 00:09 oknoorap

Also getting this. Using fs in getStaticProps to fetch images from api and save to ./public/api_images/, when I then use require('../public/api_images/my_image.png') I get an error saying Error: Cannot find module './api_images/my_image.png'

Edit: To clarify, the project build just fine and is able to find all images if use a regular string as src for the <img> tag instead of the require() that this package calls for.

andree-rehnberg avatar Oct 11 '20 18:10 andree-rehnberg

I've fixed this project with alias:

module.exports = withFonts(
  withOptimizedImages(
    {
      webpack: (config) => {
        config.resolve.alias['@public'] = path.resolve(__dirname, 'public');
        return config;
      },
    }
  )
);

Then you can do <img src={require('@public/images/hero/my-image.jpg?webp')} />

ka8725 avatar Oct 31 '20 20:10 ka8725

having the same issue with nextJS 10

wadhah101 avatar Dec 28 '20 21:12 wadhah101