question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Resizing images usage

See original GitHub issue

Expectation

I should be able to resize images in development after installing responsive-loader and sharp, with no additional configuration in next.config.js.

Result

Images are not optimized in dev when I do:

<img src={`${src}?resize&size=300`} />

or using require gives me Cannot find module error:

<img src={require(`${src}?resize&size=300`)} />

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:2
  • Comments:6 (6 by maintainers)

github_iconTop GitHub Comments

3reactions
cyrilwannercommented, Mar 6, 2019

Okay, I think this error now comes from defining the two webpack configs as plugin options. It may work with only a single one, but when using more than one, it actually overwrites the other one (and all other webpack config changes the plugins do internally, so the typescript plugin doesn’t to anything anymore). It has to do how next parses the config file: It doesn’t merge duplicate properties, it just overwrites them. I’m not sure if I can hook into that from within this plugin, I will try it but the current version can’t handle it.

To solve it, you can move the webpack configs out of the plugin configs into the global config object (2. param):

module.exports = withPlugins([
  [withFonts, {}],
  [withTypescript],
  [
    optimizedImages,
    {
      optimizeImagesInDev: true,
    }
  ]
], {
  webpack(config, options) {
    // only add plugin in development to client webpack config .
    if (env === "development" && !options.isServer) {
      config.plugins.push(new ForkTsCheckerWebpackPlugin());
    }

    // add a resolve alias for the static folder
    config.resolve.alias["static"] = path.join(__dirname, "static");

    return config;
  }
});

I’ll try to change the plugin to also work with your definition of the plugins in the future, I like that way of overwriting the webpack config so they are next to the relevant plugin 😃

3reactions
cyrilwannercommented, Feb 28, 2019

I think there are actually two problems. The first one is, that you use absolute paths (/static/...) instead of relative ones (../../static/...). When importing an image, the same rules apply as when importing a js file. You also can’t import a regular js file with an absolute path (/components/MyComp.js), this is simply a restriction by webpack and also applies to images. Someone else had the same problem just recently: #62

Now, there are two solutions to solve this: you could just change the paths to relative ones (but you may end up with a lot ../../ depending where you are) or you add a path alias to webpack (as mentioned in the referenced issue above). So, adding something like this to your next.config.js allows you to use almost absolute paths, you just have to remove the first slash (static/... instead of /static/...):

webpack(config, options) {
  config.resolve.alias['static'] = path.join(__dirname, 'static')
  return config
}

This should solve the first problem. Then, the second one is, as you also wrote in your last comment, the same as in issue #16. Although, this is also a webpack restriction, next-optimized-images can’t avoid this. And when you also want to use a query string (?resize) together with a dynamic path, it gets even more complicated and you have to use a require context (https://github.com/cyrilwanner/next-optimized-images/issues/16#issuecomment-405556547).

So, I think something like this could work:

const listings = [
  {
    src: "./1/preview.jpg",
  },
  {
    src: "./2/preview.jpg",
  },
  {
    src: "./3/preview.jpg",
  },
  {
    src: "./4/preview.jpg",
  }
];

//                                              v this requires you to define the path alias in webpack, otherwise, you can also use a relative path here
const requireResizedImage = require.context('static/images/listings/?resize&size=300', false, /\.jpg$/);


const listingsMarkup = listings.map(({ src, breed, gender, id }) => (
  <Preview
    src={requireResizedImage(src)}
    key={src}
  />
));

There is just one downside: Because webpack doesn’t know which images you need at runtime, it resizes all images in the directory you pass in to the require.context function (means in static/images/listings/). If you have many images in there, the build could take much longer. If this is the case, I recommend creating a new directory which only contains the images you actually need resized (e.g. static/images/listings-thumbnails/).

I hope that this helps solving your issue 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Free Image Resizer: Resize Photos Online | Adobe Express
Resize your photos easily with the Adobe Express free image resizer. Simply upload your pictures, change the photo size, and download your new...
Read more >
What is Resizing? - All About Images - Research Guides
When an image is resized, its pixel information is changed. For example, an image is reduced in size, any unneeded pixel information will...
Read more >
How to Resize an Image Correctly | The TechSmith Blog
Use photo editing software to resize your image · Avoid stretching or distorting your images by locking the aspect ratio before making adjustments....
Read more >
How to resize your images quickly and easily | ZDNET
1. Open image. Open Photoshop and click File > Open… Then find your image on your PC or Mac and click Open. ·...
Read more >
Simple Image Resizer, resize online images without losing ...
Simple Image Resizer is free, online and powerful image resizer. Resize your images, photos, scanned documents without losing quality and in a easy...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found