Replies: 42 comments 70 replies
{{title}}
{{editor}}'s edit
{{editor}}'s edit
-
I actually expected this functionality when I tried out next/image. Then when it didn't work I couldn't find anything about it in the docs. Would be really great if next/image worked with export |
Beta Was this translation helpful? Give feedback.
-
Why was this issue moved to discussion? What's the difference between "Feature request" label under issues and the "Ideas" label under discussion? |
Beta Was this translation helpful? Give feedback.
{{title}}
{{editor}}'s edit
{{editor}}'s edit
-
Any plans of supporting this feature in near future?
cc: @leerob @timneutkens |
Beta Was this translation helpful? Give feedback.
-
Next is claiming that it supports static side generation. It is also proud of providing image optimization. Now I had to learn the hard way after converting my code from Gatsby to Next, that we cannot have both even though it is part of the core library. That is a real bummer. @timneutkens I have found this idea here only after I started writing a feature request and started looking for a similar request at this place (didn't find one on the issues). So please don't take the Also, maintainers are closing related issues because this functionality is intended, which makes them and this discussion thread harder to find and reduces the interactions with these. There are several issues pointing to this missing feature: ... just to name a few I was able to find without investing too much time. Generating these images during export should be provided by Next. Resizing images using NodeJS is already implemented (used by next start) and we only need to generate resolution sensitive image tags in the static HTML plus the image files. Since this is OSS: Can I help somehow? |
Beta Was this translation helpful? Give feedback.
-
Yup, it's a problem, especially when it's not being handled at all. Not only it does not optimize images, but actually brakes the generated static site. I'm really surprised there's still no huge red warning in the docs (1, 2) that using Did anybody try using Netlify with |
Beta Was this translation helpful? Give feedback.
-
We've got a naive but workable workaround in https://github.com/minvws/nl-covid19-data-dashboard/pull/1434/files#diff-f9318ad2bcfcfdc021518b7d9f7c102c4b32461be1c838a624595d100c6ef5c5 This would be easier if this was built-in, for sure. |
Beta Was this translation helpful? Give feedback.
-
Same here... for us the whole point of choosing Next.js was the ability to |
Beta Was this translation helpful? Give feedback.
-
The issues is still open and no possible fixes yet. I only used Next.js for it's image optimization, but had to learn myself that it won't work on export |
Beta Was this translation helpful? Give feedback.
-
On the one hand, next.js docs say:
And then, on the other,
It seems to me it only works this way because Vercel offers a premium image optimisation service. If next.js optimised images at build time, then they fear losing customers. This is mind boggling. I've been thinking for a few days whether to go with next.js or gatsby for a new project. This settles it. |
Beta Was this translation helpful? Give feedback.
-
Based on the number of upvotes and thumbs up on this idea, this is the 2nd most requested feature on Next.js right now. Come on, please give us some sort of announcement that this feature is coming and when we can expect it. I was ready to switch from Gatsby to Next.js, and was completely baffled that the seemingly simple requirement to have I don't want to completely change my hosting provider and webserver configuration just for an on-demand image optimization feature that I don't need, and I don't like the security implications of having a Node.js app run permanently on a public server. What if a security flaw is discovered in some Node.js networking functionality? To me, one of the huge benefits of having an entirely static site is not having to worry about security updates anymore. Requiring a permanently running Node.js app for an essential web feature like images completely defeats this benefit. |
Beta Was this translation helpful? Give feedback.
-
I recently bumped into this issue as well and was surprised to find out that Despite there being a workaround, it would be great to have the ability to optimize images during build out of the box and without having to jump through additional hoops. Also, highlighting the limitations of |
Beta Was this translation helpful? Give feedback.
{{title}}
{{editor}}'s edit
{{editor}}'s edit
-
Edit: I've updated the main discussion with the latest updates |
Beta Was this translation helpful? Give feedback.
-
I've only recently switched to using Next/Image, but I bumped into this rather quickly. It's not just next export, it would be nice to be able to generate optimized images during build time in general, so that users don't have to wait 2-3 seconds for important images to load the first time they visit the site. Similar to how we can statically generate pages during build time, optimizing images seems like a reasonable next step. Some people rely quite heavily on static generation, with frequent rebuilds, and the images need to be recreated after every build, so they experience this initial delay quite regularly. The easy way to deal with this is to just open the important pages once after each rebuild and scroll through them, and screw around with your browser width so that all the important images get generated at different sizes, but there has to be a more elegant way. |
Beta Was this translation helpful? Give feedback.
This comment was marked as spam.
This comment was marked as spam.
-
I would love this future, currently i am stuck as I need all images to be bundled into the build. Reason why i would need this feature for this current project: Do anyone know of any workarounds? |
Beta Was this translation helpful? Give feedback.
-
I gave it a go to create a solution for optimized images for use with the Next.js static export. The library wraps the <Image /> component of Next.js and automatically creates optimized images using sharp.js at build time. The solution is heavily inspired by @nvh95's suggestion. You can find all details in this npm package: https://www.npmjs.com/package/next-image-export-optimizer In short, it uses a custom loader to create a srcset for the <img /> that the <Image /> component of Next.js creates. Then at build/export time, the images inside the public/images folder (as an example) are optimized with sharp.js and copied into the build folder. Please give it a go. (it is my first open-source contribution, so I am sure there is room for a lot of improvement) |
Beta Was this translation helpful? Give feedback.
-
Since In
Define the following custom loader const exportableLoader = ({ src, width, quality }: ImageLoaderProps) => {
if (process.env.NODE_ENV === 'development') {
// This doesn't bother optimizing in the dev environment. Next complains if the
// returned URL doesn't have a width in it, so adding it as a throwaway
return `${src}?width=${width}`
}
// Generate a reasonably unique base folder. Doesn't have to be perfectly unique
const [path, extension] = src.split(/\.([^.]*$)/) || []
if (!path || !extension) {
throw new Error(`Invalid path or no file extension: ${src}`)
}
const filename = path.match(/([^\/]+)$/)?.[1] || ''
const output = `/_optimized${path}/${filename}_${width}_${quality || 75}.${extension}`
if (typeof window === 'undefined') {
const json = { output, src, width, quality: quality || 75 }
const fs = require('fs')
const path = require('path')
fs.appendFileSync(
path.join(process.env.DIRNAME, '.next/custom-optimized-images.nd.json'),
JSON.stringify(json) + '\n'
)
}
return output
} Pass this loader to every instance of When you run Next, run The last step is to optimize the images. Run import fs from 'fs/promises'
import path from 'path'
import { fileURLToPath } from 'url'
import Jimp from 'jimp'
const __dirname = fileURLToPath(new URL('.', import.meta.url))
optimize()
async function optimize() {
const outPath = 'out'
const items = (
await fs.readFile(
path.join(__dirname, '.next/custom-optimized-images.nd.json'),
'utf-8'
)
)
.trim()
.split(/\n/g)
.map((line) => JSON.parse(line))
await Promise.all(
items.map(async (item) => {
const srcPath = path.join(__dirname, outPath, item.src)
const destPath = path.join(__dirname, outPath, item.output)
console.log({ srcPath, destPath })
const img = await Jimp.read(srcPath)
await img.resize(item.width, Jimp.AUTO)
await img.quality(item.quality)
await img.writeAsync(destPath)
})
)
} |
Beta Was this translation helpful? Give feedback.
This comment was marked as off-topic.
This comment was marked as off-topic.
{{title}}
{{editor}}'s edit
{{editor}}'s edit
-
This really needs some sane defaults. I get warnings and failed builds if I try using an I don't even want image optimization at this point I just want to export my website, but this issue causes build errors and all my attempted workarounds with custom loaders and config found during hours of sifting through GitHub comments have just led to more errors. |
Beta Was this translation helpful? Give feedback.
-
Boy am I happy I've spent 6 hours of my life trying to get a static site generator to optimize static images. So far I have two solutions. Both are kinda nasty, and require you to disable the
If anyone is interested in the manual optimization script let me know and I'll dump what I've got thus far. It's pretty smelly but I'll probably stick with it for the time being just to avoid fiddling with webpack and breaking something else. But just to reiterate what everyone else is saying: it is absolutely wild that Next doesn't support this stuff out of the box. Are you guys getting royalties from Cloudinary? :P I don't think it's fair to continue to market Next as a SSG when it can't handle local images properly. |
Beta Was this translation helpful? Give feedback.
This comment was marked as off-topic.
This comment was marked as off-topic.
-
We have built a solution to optimize images at build time and released it under the MIT license! Using this repository, you can get the full benefits of next/image even when using next export by doing image optimization at build time. This makes it possible to build a high performance website with this solution, whether you want to build a simple website or a completely static output. As a special note,
This solution was inspired by @jkjustjoshing's suggestion. |
Beta Was this translation helpful? Give feedback.
-
More info in README.md, site available here: https://www.terezemedne.com/ |
Beta Was this translation helpful? Give feedback.
-
We've just released sidepix, a picture (as in At Neugelb we've been using a version of sidepix in production, but the open source version is rather different, arguably improved but also less tested. We'll be adding documentation and minor features in the next weeks. Of course, any feedback is welcome! |
Beta Was this translation helpful? Give feedback.
-
Ended up by writing JS script (gulp task) which searches for project images (using globby), then resizes them using imagemagick and builds JSON with module.exports = {
"Products": {
"decode": {
"images": {
"main01Open": {
"srcSet": "/generated/pages/products/decode/images/main-01-open-e9e51a84-300.png 300w,/generated/pages/products/decode/images/main-01-open-e9e51a84-320.png 320w,/generated/pages/products/decode/images/main-01-open-e9e51a84-640.png 640w,/generated/pages/products/decode/images/main-01-open-e9e51a84-960.png 960w,/generated/pages/products/decode/images/main-01-open-e9e51a84-1200.png 1200w",
"src": "/generated/pages/products/decode/images/main-01-open-e9e51a84-640.png"
},
....
}
}
}
} Usage: <img
src={Assets.Products.decode.images.main01Open.src}
srcSet={Assets.Products.decode.images.main01Open.srcSet}
alt="Opening Xib or Storyboard."
/> |
Beta Was this translation helpful? Give feedback.
This comment was marked as off-topic.
This comment was marked as off-topic.
This comment was marked as off-topic.
This comment was marked as off-topic.
{{title}}
{{editor}}'s edit
{{editor}}'s edit
-
I've updated the main message with more details - also:
Please keep the conversation on topic, upvoting current solutions or options for build-time image optimization. Thank you! |
Beta Was this translation helpful? Give feedback.
{{title}}
{{editor}}'s edit
{{editor}}'s edit
-
Edit: This post has been updated by @leerob to include the current solutions and related issues.
Overview
next/image
does not currently perform image optimization duringnext build
, and instead optimizes images on-demand. This was done to prevent long build times when optimizing many images. Build time optimization is one of the top requests from the community and is something we're exploring solutions for. In the meantime, here are the current solutions.Current Solutions
Static Exports
Image Optimization through
next/image
can still be used with a static export by defining a custom image loader innext.config.js
. For example, you can optimize images with a service like Cloudinary:This custom loader will define how to fetch images from a remote source. For example, the following loader will construct the URL for Cloudinary:
You can then use
next/image
in your application, defining relative paths to the image in Cloudinary:Disabling Optimization
If you want to use
next/image
(for maintaining aspect ratio, etc) but don't want any image optimization, you can opt-out as of 12.3:Checking optimized images into git
You optimize your images are part of a separate pipeline and check those files into git for consumption in your
public
folder. This is a good solution if you are worried about build times, as they compute and run on your local machine pre-commit. This ensures there's no build time overhead.Related Issues
#18356
Beta Was this translation helpful? Give feedback.
All reactions