Giter Site home page Giter Site logo

dc7290 / next-export-optimize-images Goto Github PK

View Code? Open in Web Editor NEW
325.0 0.0 28.0 12.91 MB

Optimize images at build time with Next.js.

Home Page: https://next-export-optimize-images.vercel.app

License: MIT License

JavaScript 25.29% Shell 0.43% TypeScript 74.28%
nextjs optimization typescript

next-export-optimize-images's Introduction

npm downloads License Node.js CI GitHub Repo stars

Next Export Optimize Images

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.

Feature

  • Optimize images at build time.
  • All options for next/image available
  • Convert formats (png → webp, etc.)
  • Download external images locally.
  • Using sharp, so it's fast.
  • Cache prevents repeating the same optimization
  • Support TypeScript
  • Support AppRouter

Installation

yarn add -D next-export-optimize-images

Document Site

https://next-export-optimize-images.vercel.app

License

Next Export Optimize Images is available under the MIT License.

next-export-optimize-images's People

Contributors

ajhawkings avatar batazor avatar boylec avatar dc7290 avatar dependabot[bot] avatar gp2mv3 avatar itsmejoeeey avatar julian avatar knemerzitski avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

next-export-optimize-images's Issues

"Successful optimization!" message shows even when there are errored assets

Describe the bug
"Successful optimization!" message shows even when there are errored assets. Here's a log snippet:

[Error: ENOENT: no such file or directory, open '/home/ben/Projects/infra-config/website/out/out/_{
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '/home/ben/Projects/infra-config/website/out/out/_next/static/media/goose-with-computer-da'
}
[Error: ENOENT: no such file or directory, open '/home/ben/Projects/infra-config/website/out/out/_{
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '/home/ben/Projects/infra-config/website/out/out/_next/static/media/goose-with-computer-da'
Cache assets: 192, NonCache assets: 0, Error assets: 128
[Error: ENOENT: no such file or directory, open '/home/ben/Projects/infra-config/website/out/out/_{
Successful optimization!

To Reproduce

  1. Make image optimization fail. In my case, I set basePath in next.config.js but didn't set it in export-images.config.js
  2. Observe a successful exit status

Expected behavior
Expected the process to return a nonzero exit status when there are error assets.

Screenshots
image

Desktop (please complete the following information):

  • OS: Ubuntu 20.04
  • Browser: N/A
  • Version: N/A

Error with NX monorepo

Describe the bug
Page with next/image throw error -> ENOENT: no such file or directory

To Reproduce
export with nx monorepo

Expected behavior
export to happen

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: MacOS
  • Browser -
  • Version - nx 14.8.4

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context

[    ] info  - Generating static pages (0/5)Error: ENOENT: no such file or directory, open '/Users/az/GitHub/websites-monorepo/.next/custom-optimized-images.nd.json'
    at Object.openSync (node:fs:594:3)
    at Object.writeFileSync (node:fs:2207:35)
    at Object.appendFileSync (node:fs:2269:6)
    at exportableLoader (/Users/az/GitHub/websites-monorepo/dist/apps/digitalizzato/.next/server/chunks/233.js:3097:4906)
    at _tmp (/Users/az/GitHub/websites-monorepo/dist/apps/digitalizzato/.next/server/chunks/233.js:3184:24)
    at /Users/az/GitHub/websites-monorepo/dist/apps/digitalizzato/.next/server/chunks/233.js:3567:39
    at Array.map (<anonymous>)
    at generateImgAttrs (/Users/az/GitHub/websites-monorepo/dist/apps/digitalizzato/.next/server/chunks/233.js:3567:24)
    at ImageElement (/Users/az/GitHub/websites-monorepo/dist/apps/digitalizzato/.next/server/chunks/233.js:3699:183)
    at Wc (/Users/az/GitHub/websites-monorepo/node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:68:44) {
  errno: -2,
  syscall: 'open',
  code: 'ENOENT',
  path: '/Users/az/GitHub/websites-monorepo/.next/custom-optimized-images.nd.json'
}

Error occurred prerendering page "/image-test". Read more: https://nextjs.org/docs/messages/prerender-error
Error: ENOENT: no such file or directory, open '/Users/az/GitHub/websites-monorepo/.next/custom-optimized-images.nd.json'
    at Object.openSync (node:fs:594:3)
    at Object.writeFileSync (node:fs:2207:35)
    at Object.appendFileSync (node:fs:2269:6)
    at exportableLoader (/Users/az/GitHub/websites-monorepo/dist/apps/digitalizzato/.next/server/chunks/233.js:3097:4906)
    at _tmp (/Users/az/GitHub/websites-monorepo/dist/apps/digitalizzato/.next/server/chunks/233.js:3184:24)
    at /Users/az/GitHub/websites-monorepo/dist/apps/digitalizzato/.next/server/chunks/233.js:3567:39
    at Array.map (<anonymous>)
    at generateImgAttrs (/Users/az/GitHub/websites-monorepo/dist/apps/digitalizzato/.next/server/chunks/233.js:3567:24)
    at ImageElement (/Users/az/GitHub/websites-monorepo/dist/apps/digitalizzato/.next/server/chunks/233.js:3699:183)
    at Wc (/Users/az/GitHub/websites-monorepo/node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:68:44)
info  - Generating static pages (5/5)

No images were found to optimize although I use Image-component in code

First of all thank you for your work on this. It is exactly what I need in my Next.js project in combination with a headless cms. Unfortunately I do have an issue I cannot resolve. I hope you can help me.

Describe the bug
Although I use the Image component from next/image in my code I keep getting the 'No images were found to optimize. (Maybe you never used the image component.)' console log during next export. I noticed that there is also no file custom-optimized-images.nd.json in my .next folder. I suppose this is generated during next build.

To Reproduce
Steps to reproduce the behavior:

  1. Use Image component in the code
  2. Build the app via next build (or BASE_PATH=staging npx env-cmd -f ./environments/.env.staging next build in my case)
  3. Export the app via next export and optimize image via next export && next-export-optimize-images
  4. Console log shows No images were found to optimize. (Maybe you never used the image component.)
    image

Expected behavior
Find Image components and optimize used images from code.

Additional context
I use the Image component like this:
image
The source of the image is an external url directly from the cms.

The first time I did a local build and export, I saw the external images were downloaded but after that I only see the above notification.

'basePath' config is ignored when running 'next dev'

Hi,
I've ran into an issue when using both next dev and basePath.

Describe the bug
basePath config is ignored when using next dev

To Reproduce
Steps to reproduce the behavior:

  1. Create an new next project and add next-export-optimize-images
  2. Add basePath: '/docs' to both config files
  3. Run next dev to run the dev server and navigate to http://localhost:3000/docs
  4. The nextjs logo fails to load because /docs/ is missing from the <img> url

image

The workaround is the remove the basePath config during development.

Expected behavior
Images should be displayed properly when using next dev

Additional context
next 13.4.10
next-export-optimize-images 3.1.0

Optimise by serving multiple formats

Thank you so much for the library!

Is your feature request related to a problem? Please describe.
I want to be able to serve next gen formats (webp, avif) to those on compatible browsers while allowing for a fallback to jpg/png for those on incompatible browsers.

Describe the solution you'd like
I provide a jpeg/png image. The library converts those images to webp/avif in the relevant sizes and serves all of the possible formats in all possible sizes, depending on what the browser supports.
Similar to the current convert formats functionality, but supporting multiple formats and serving optimised images from the original format too.

Describe alternatives you've considered
https://github.com/Niels-IO/next-image-export-optimizer supports this.

Additional context
The functionality I am looking for is the same that is available in next.js - see: https://nextjs.org/docs/app/api-reference/components/image#formats

Images within client-side-only loaded components aren’t optimized

Images within client-side-only loaded components aren’t optimized. For example:

✅ This works

import dynamic from 'next/dynamic';
import type { NextPage } from 'next';
import ComponentWithImage from './ComponentWithImage';

export const Page: NextPage = () => (
  <main>
    <h1>Title</h1>
    <ComponentWithImage />
  </main>
);

❌ This doesn't work

import dynamic from 'next/dynamic';
import type { NextPage } from 'next';

const ClientSideComponentWithImage = dynamic(
  async () => await import('./ComponentWithImage'),
  { ssr: false }, // The problem
);

export const Page: NextPage = () => (
  <main>
    <h1>Title</h1>
    <ClientSideComponentWithImage />
  </main>
);

The .next/custom-optimized-images.nd.json manifest isn't populated with the dynamic images during next build.

Unable to optimize images if `experimental.images.unoptimized` is true

Describe the bug
If experimental.images.unoptimized is true, the custom-optimized-images.nd.json file is not generated and, therefore, an error is thrown when trying to resolve the manifest path:

image

To Reproduce
Steps to reproduce the behavior:

  1. Add experimental.images.unoptimized to any next.config
  2. Execute the build scripts
  3. See error (logged as "unexpected error")

Expected behavior
Two options:

  1. The library should warn the user about this invalid option
  2. The library should override this config

Screenshots
See above

Add support for build cache

When building a larger project, it can be quite time consuming to optimise images for each build. Is there a way to implement build caching into this library in order to save time when generating static builds.

For example, Cloudflare now has build caching and all cached files are stored in the .next/cache folder. Is there any way to utilise this folder and store images that will be used across builds?

Thanks!

Webp animation breaks after export

Describe the bug
After the export, the webp animation is removed and only the first frame remains.

To Reproduce
Just export animated webp image

Expected behavior
Animation plays just like the original

Does not export images in conditionally rendered components

Describe the bug
I've recently started using next-export-optimize-images, and have arrived at the issue that images in conditionally rendered components, such as a modal or different component view, do not export and gives me 404 error for any images that are meant to be in these types of components. It looks like the src and srcset are renamed, but the images are missing.

To Reproduce
Steps to reproduce the behavior:

  1. Create a conditionally rendered component (e.g. using state)
  2. Build app
  3. Open relevant page
  4. Toggle the component to be shown
  5. Images give 404 error

Expected behavior
Images to be exported and optimised in conditionally rendered components. Not get a 404 error.

Screenshots
Screenshot 2023-07-14 at 12 14 11
Screenshot 2023-07-14 at 12 08 29
Screenshot 2023-07-14 at 12 12 12

Desktop (please complete the following information):

  • OS: macOS 13.2.1
  • Browser: Chrome
  • Version: 114.0.5735.198

Element type is invalid

Describe the bug
I get errors with the latest version in client components.
As soon as I add an "use client" block I get the following error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `ForwardRef(CustomImage)`.

This seems to have been introduced with version 3. It worked with version 2 and an older version of nextjs (13.4.1).
I'm running next: 13.4.8 but you can also see the same error with next: 13.4.9.

To Reproduce
Steps to reproduce the behavior:

  1. Create a custom client component with "use client" at the top of the file
  2. Import an image src
  3. Add it to the the next/image component
  4. See error

Expected behavior
No error

Incompatibility Issue between Bun and Next-Export-Optimize-Images with Sharp Module

Describe the bug

When building a Next.js project using bun, an incompatibility issue arises between next-export-optimize-images and the sharp module. Specifically, an error occurs during the installation of the sharp module, leading to the interruption of the build process.

To Reproduce

Steps to reproduce the behavior:

  1. Run bun run build in the terminal.
  2. Observe that the command next build && next-export-optimize-images is executed.
  3. Notice the error during the build process.

Expected behavior

The sharp module should install correctly, and the build process should complete successfully.

Error Log

Error: 
〜/node_modules/next-export-optimize-images/node_modules/sharp/lib/sharp.js:37
  throw new Error(help.join('\n'));
  
Something went wrong installing the "sharp" module

Cannot find module '../build/Release/sharp-darwin-arm64v8.node'
Require stack:
- ~/pakistan-pjh.com/node_modules/next-export-optimize-images/node_modules/sharp/lib/sharp.js
- ~/pakistan-pjh.com/node_modules/next-export-optimize-images/node_modules/sharp/lib/constructor.js
...

Possible solutions:
- Install with verbose logging and look for errors: "npm install --ignore-scripts=false --foreground-scripts --verbose sharp"
- Install for the current darwin-arm64v8 runtime: "npm install --platform=darwin --arch=arm64v8 sharp"
- Consult the installation documentation: https://sharp.pixelplumbing.com/install
...

Node.js v18.16.1
error: script "build" exited with code 1 (SIGHUP)

Desktop (please complete the following information):

OS: macOS Sonoma 14.1.1 (m1)
Node.js Version: 18.16.1
Bun Version: 1.0.15

Additional context

This issue seems specific to the use of bun for building, as the build process completes successfully when using traditional Node.js tools like npm or yarn. 🧐

Next v12 project not supported

Describe the bug

When creating a Next.js project running v12, an error appears when installing next-export-optimize-images.

Can we make an update to prevent this error, without needing to install with --force, or --legacy-peer-deps?

To Reproduce

npx create-next-app@12 my-new-app
cd my-new-app
npm i next@12
npm i next-export-optimize-images --save-dev   

Expected behaviour

No errors from the console expected when installing the next-export-optimize-images package.

Console output

╰─ npm i next-export-optimize-images --save-dev                                                                                                                                                                                                                                                                 ─╯
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/next
npm ERR!   next@"12.1.6" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer next@"^13.3.2" from [email protected]
npm ERR! node_modules/next-export-optimize-images
npm ERR!   dev next-export-optimize-images@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Desktop:

  • OS: macOS Ventura v13.4

`No images were found to optimize.` error message on Next.js 13.2.3

Just tried the package for the first time and cannot get it to find/optimize any images. I've searched through all other issues and have tried using running it both with next build && next-export-optimize-images and next build && next export && next-export-optimize-images, both yielding the same error message.

I'm on Next.js 13.2.3 and are using the new next/image without any custom loaders. The compiled image component do point to the correct paths, but cannot be resolved since the optimization part never gets run.

Reviewing the source code I guess it must have to do with that the manifestJsonPath cannot be resolved for some reason? Have something changed with the newest versions of Next.js or am I missing something?

Monorepo構成にしている場合にエラーになる

日本語ですみません。。

Describe the bug
yarnでworkspaceを利用して、Monorepo構成にしている場合にエラーになってしまいます。

To Reproduce

  1. yarnでworkspaceを利用してworkspaceにpackage1package2を追加(依存packageはmonorepo/node_modules配下で管理される)
  2. package1のみでNext.jsを使用するため、package1配下にnext.config.js、export-images.config.jsを配置
  3. next build && next export && next-export-optimize-imagesを実行
  4. 以下のエラーが出る
warn  - ../node_modules/next-export-optimize-images/dist/utils/getConfig.js
Module not found: Can't resolve 'next-export-optimize-images/export-images.config.js' in '/Users/monorepo/node_modules/next-export-optimize-images/dist/utils'

Desktop (please complete the following information):

  • node version 18.3.0
  • macOS Big Sur 11.2.3
  • Next.js version 12.2.0
  • next-export-optimize-images version 1.5.3

Expected behavior
原因としては、copyConfig.jsの書き出し先のパスと、getConfig.jsの読み込み先のパスに相違があることが考えられます。
copyConfig.jsはmonorepo/package1/node_modules/next-export-optimize-images/export-images.config.jsを作成し、
getConfig.jsはmonorepo/node_modules/next-export-optimize-images/export-images.config.jsを読みに行っているようです。

next.config.jsがある階層のnode_modulesのパスをgetConfigで読んで欲しいです。

構成のイメージは下記です。

monorepo
├── package1
│   ├── node_modules
│   │    └── next-export-optimize-images
│   │        └── export-images.config.js # ここに書き出される
│   ├── next.config.js
│   ├── export-images.config.js
│   └── package.json
├── package2
│   └── ...
├── package.json
└── node_modules
     └── next-export-optimize-images
          ├── bin
          ├── dist
          └── ...

Support Image use in server components

Describe the bug

  • relevant dependencies:
"next": "13.4.2",
"react": "18.2.0",
"react-dom": "18.2.0"
"next-export-optimize-images": "^2.1.0",
  • I'm using the new app directory router with its server components
  • I'm using the current version of next/image (not the legacy one)

When I install the next-export-optimize-images and update the next.config.js, I'm getting this:

- error node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-server.edge.development.js (1912:12) @ resolveModelToJSON
- error Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server".
  <... src={{...}} alt=... unoptimized=... fill=... className=... priority=... loader={function} blurDataURL=...>
                                                                                      ^^^^^^^^^^
    at stringify (<anonymous>)
null

=> it seems the server component are not yet supported. Please, would it be possible to add the support?

Thank you for this project!

convertFormat option does not exchange fileNames in HTML

Description

I am using the remoteImages async method to dynamically get the image url array from our CMS. Additionally i have configured the "convertFormat" option like:

convertFormat: [['png', 'webp']],

The download including the generation of the images are working quite fine and all the PNG files are converted into WEBP like this:
image

The problem now is that none of my images are shown on the page in production build cause the resulting image tag is still using the ".png" extension like this:

<img alt="" loading="lazy" decoding="async" data-nimg="fill" class="s-object-cover" style="position: absolute; height: 100%; width: 100%; inset: 0px;" sizes="100vw" srcset="/_next/static/chunks/images/image_2_386f0019ef_640.png 640w, /_next/static/chunks/images/image_2_386f0019ef_750.png 750w, /_next/static/chunks/images/image_2_386f0019ef_828.png 828w, /_next/static/chunks/images/image_2_386f0019ef_1080.png 1080w, /_next/static/chunks/images/image_2_386f0019ef_1200.png 1200w, /_next/static/chunks/images/image_2_386f0019ef_1920.png 1920w, /_next/static/chunks/images/image_2_386f0019ef_2048.png 2048w, /_next/static/chunks/images/image_2_386f0019ef_3840.png 3840w" src="/_next/static/chunks/images/image_2_386f0019ef_3840.png">

Is there anything I am may missing in the config or is the convertFormat option not working in combination with remoteImages?
I would be glad to have a solution for this!

Thanks for your help and BR

Part of `export-images.config.js` does not work

We are currently investigating, but the following features do not seem to be working.

  • basePath
  • sourceImageParser
  • convertFormat
  • imageDir
  • externalImageDir
  • filenameGenerator

Perhaps there is a phenomenon where export-images.config.js cannot be loaded during the HTML generation phase in the next build.

ToDo: Create an image loader and optimize images for components that are not evaluated at build time.

Currently, with this library, images can be optimized at build time using next/image.
However, images are not optimized for components that cannot be evaluated at build time.
For example, components that are loaded only on the client side using next/dynamic, or components whose rendering is controlled using useState, etc.

To address this, we believe that static analysis is necessary and would like to use the SWC code conversion used in Next.js to detect images that cannot be evaluated at build time before they are built.

Add info to documentation regarding supported file type

When using this package, it appears that all files that import Image must be of type “.jsx”. (I got a build error when using images with a file of type “.js”.)

If the files must be of type “.jsx”, can you add that information to the documentation?

Invalidate cache after config change

Is your feature request related to a problem? Please describe.
When I change sharpOptions (e.g. enable progressive), the image optimizer still uses the cached images.

Describe the solution you'd like
Invalidate cache when options change.

Describe alternatives you've considered
Disable caching on my CI pipeline so that we don't run into this issue in production.

Images with width less than 100px not showing when next exported and served

Describe the bug
Images with width less than 100px are not displaying when exported

To Reproduce
Steps to reproduce the behavior:

  1. Use 50 as width and height of the next/image component
  2. run next build && next export && next-export-optimize-images
  3. To test, run npx http-server out
 <Image src="/images/icons/csv.svg" width={50} height={50}  />

Expected behavior
The image should display when it is exported and served

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: macOS
  • Browser chrome, safari
  • Version [105.0.5195.125 (Official Build) (arm64)]

SVG is not a valid image file error with inline @svgr/webpack

Describe the bug
SVG is not a valid image file error with inline using @svgr/webpack. Here is the error message

Error: Image import "@svg/Android.svg" is not a valid image file. The image may be corrupted or an unsupported format.

Should have fixed here #658 but maybe happening again with the current next version?

Expected behavior
Should treat SVG as same as other formats

Desktop (please complete the following information):

  • OS: macOS
  • Browser: chrome

Package versions

  • "next-export-optimize-images": "^3.2.0"
  • "next": "^14.0.4"

No images were found to optimize error when using external images & custom loader

Describe the bug
As soon as I add a custom loader, next-export-optimize-images no longer detects any images to download. As soon as it is removed, everything works fine again. It does not matter what the loader actually does, even a function simply returning the input src will stop it from working.

It's perhaps worth mentioning that I'm using external images from a CDN. It has been whitelisted in next.config.js, and as previously mentioned it works fine without the loader.

Any help or ideas would be greatly appreciated, this plugin looks like exactly what we need :) Thanks!

To Reproduce
Steps to reproduce the behavior:

  1. Add a custom loader to an image component:
    import NextImage, { ImageLoaderProps, ImageProps } from 'next/image'
    
    const dummyLoader = ({ src }: ImageLoaderProps) => src
    export const Image = (props: ImageProps) => <NextImage loader={dummyLoader} {...props} />
  2. Build & export
  3. No images are downloaded. next-export-optimize-images exits with the message No images were found to optimize.

Expected behavior
Images should be properly collected, downloaded and optimized even when a custom loader is provided.

Additional information
The entire site is pre-rendered using Nextjs Static Site Optimization.

out of memory with too many/big images

when i run next-optimized-images with a lot of images on a machine with 16gb ram, it crashes and i am getting this error:

ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL  Command was killed with SIGKILL (Forced termination): next-export-op

i think the issue is loading same images for different sizes multiple times. so i changed it to load image one time for one src and use it for creating different size images and it worked without crashes.

Hangs when there's an svg file

Describe the bug
If there's an svg, it just hangs and never finishes. The logs say it's not a supported file type. You should be able to just output the source file if it's not supported.

To Reproduce
<Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />

Expected behavior
Should work just like the built-in server-side optimization.

Screenshots
Screen Shot 2022-06-08 at 2 22 16 PM

Desktop (please complete the following information):
MacOS
Node v14.18.3

Is it possible to exclude some images from optimization?

Is your feature request related to a problem? Please describe.
In my Nextjs application some images are webp animations. Once the optimisation process has run, these are rendered as static images which are not animated. I would like to disable optimisation on just these images.

Describe the solution you'd like
A way to exclude images from optimisation on an individual basis, or failing that a way to entirely exclude a file type e.g. webp.

Describe alternatives you've considered
I have tried a variety of webp configurations in sharpOptions in export-images.config.js as per the docs but so far without success.

Additional context
Also wanted to say what an awesome lib this is. Thank you very much for your efforts.

Picture support with multiple format types

Thanks for your assistance previously, it was greatly appreciated!

I'd like to suggest a new feature. If you were to add support for the picture element, one would be able to add multiple formats via sources and thus would be able to support all browsers with optimised images (e.g. Edge has no .avif support).

I prefer using .avif due to the smaller size and better quality but it would be great to be able to convert to .avif and .webp (possibly also include original) and be able to serve them within different sources in the picture tag.

<picture>
  <source
    type="image/avif"
    srcset="
      https://images.net/img-500w.avif 500w,
      https://images.net/img-900w.avif 900w...
    "
    sizes="(max-width: 735px) 100vw, 736px"
  />
  <source
    type="image/webp"
    srcset="
      https://images.net/img-500w.webp 500w,
      https://images.net/img-900w.webp 900w...
    "
    sizes="(max-width: 735px) 100vw, 736px"
  />
  <img
    srcset="
      https://images.net/.../img-500w.png 500w,
      https://images.net/.../img-900w.png 900w...
    "
    sizes="(max-width: 735px) 100vw, 736px"
    src="https://images.net/img.png"
    alt="Alt text"
    loading="lazy"
    width="2048"
    height="1024"
  />
</picture>

Do you think this is possible at all? Let me know what you think

Thank you!

Does not work with `output: 'export'`

Describe the bug
Does not work with output: 'export' on next.config.js. It was added in Next.js 13.3.

https://nextjs.org/blog/next-13-3#static-export-for-app-router

To Reproduce

  1. yarn create next-app
  2. cd my-app
  3. Edit next.config.js
  4. yarn dev

next.config.js is like this:

+const withExportImages = require("next-export-optimize-images")
+
 /** @type {import('next').NextConfig} */
 const nextConfig = {
+  output: 'export',
   reactStrictMode: true,
 }
 
-module.exports = nextConfig
+module.exports = withExportImages(nextConfig)

Expected behavior
It works with output: 'export'.

Screenshots
N/A

Desktop (please complete the following information):
N/A

Smartphone (please complete the following information):
N/A

Additional context
N/A

svg is not a valid image file

Hi,
I have some svg files in my project, and when I run next build && next-export-optimize-images will show the errors below.
Image import "@/img/icons/right.svg" is not a valid image file. The image may be corrupted or an unsupported format.
Is there any solution for this ?
thanks!

Imgur

Error: Module not found: Can't resolve 'next/dist/shared/lib/image-external'

Error

- info Loaded env from /home/sandyman/sandyman-blog/sandyman-next/.env
info - [next-export-optimize-images]: Configuration was not loaded. (This is optional.)
Failed to compile.

./node_modules/next-export-optimize-images/dist/components/image.js
Module not found: Can't resolve 'next/dist/shared/lib/image-external'

https://nextjs.org/docs/messages/module-not-found

next.config.js

/** @type {import('next').NextConfig} */
const withBundleAnalyzer = require("@next/bundle-analyzer")({
    enabled: process.env.ANALYZE === "true",
});
const withExportImages = require("next-export-optimize-images");
const nextConfig = { output: "export", trailingSlash: true };

module.exports = withBundleAnalyzer(withExportImages({ ...nextConfig }));

Environment

  • Next.js 13.4.2 (App Router)
  • next-export-optimize-images 3.2.0

Why do I get an error? Please help me😭

Type error: This expression is not callable.

Next config:

/**
 * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially useful
 * for Docker builds.
 */
await import('./src/env.mjs')

import withExportImages from 'next-export-optimize-images'

/** @type {import('next').NextConfig} */
const config = withExportImages({
  reactStrictMode: true,
  output: 'export'
})

export default config

Error:

> next build && next-export-optimize-images

- info Loaded env from DIR/.env
info - [next-export-optimize-images]: Configuration was not loaded. (This is optional.)
- info Linting and checking validity of types ..Failed to compile.

./next.config.mjs:10:16
Type error: This expression is not callable.
  Type 'typeof import("DIR/node_modules/.pnpm/[email protected][email protected][email protected][email protected]/node_modules/next-export-optimize-images/dist/index")' has no call signatures.

   8 | 
   9 | /** @type {import('next').NextConfig} */
> 10 | const config = withExportImages({
     |                ^
  11 |   reactStrictMode: true,
  12 |   output: 'export'
  13 | })
 ELIFECYCLE  Command failed with exit code 1.
 ```

List additional images to be optimized that are not rendered by a default next export

Really cool package, thanks for creating :-)

Is your feature request related to a problem? Please describe.
In a number of cases I am dynamically creating the image URL to render because of different viewport sizes as well as other reasons like errors or AJAX requests. The result is that Next is not aware of all images when doing a next export and these are not written to the JSON file of images. And subsequently next-export-optimize-images is not aware of these images and the required optimization is not done.

Describe the solution you'd like
What would be very helpful is the capability to list all extra image files along with their size and quality so next-export-optimize-images know about them and creates the optimized versions anyway.

Describe alternatives you've considered
The only way to work around this limitation seems to be to create a dummy page and add a number of <Image /> components there with all images. These would then be picked up and rendered. But that is a bit of a weird hack as that page is never supposed to be used and really should not exist.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Location: renovate.json
Error type: The renovate configuration file contains some invalid settings
Message: Invalid schedule: 'Invalid schedule: Failed to parse "after 0am on saturday"'

Automatically download remote images used in Image component

Is your feature request related to a problem? Please describe.
We are trying to build files for SSG with the option output: export.

When you only use remote images generated in a CMS, it's easy to fetch all urls and add it to remoteImages in export-image.config.js and the images will be downloaded locally.

However, it becomes a problem when you use remote images outside the CMS. You can easily mess up if you forget to add the remote url to the remoteImages list which will cause a 404 error since those images will not be downloaded on build.

Describe the solution you'd like
Download remote images used in the Image component automatically without the need to list up in remoteImages .

Describe alternatives you've considered

Additional context

==
日本語でも説明させていただきます。
前提として、next.config.jsに output: 'export' を設定してSSGする場合の課題です @nextjs13.4
リモート画像を使用する際、対象となるURLが export-images.config.js の remoteImages に含まれていないと、next build && next-export-optimize-images を実行しても画像がダウンロードされません。
CMSで管理されてる画像であればURLをまとめて取得して追加できるので漏れることはないものの、CMSで管理されていない外部の画像URLをテンプレートに直接記述するような場合は「リストに追加するのを忘れないよう頑張る」ものの、往々にして漏れて画像のリンク切れを起こしてしまいます。
そのため、Image コンポーネントで指定される外部URLを自動でダウンロードできないか、という要望です。

Blur only on string entries

Hello
Even from source the blur uri is only getting generated when the src is string. Is there any reason why it's not generated for normal require/static imports? It would be super helpful if it would and there doesnt seem to be any technical problem.

To Reproduce
Steps to reproduce the behavior:

  1. Use an imported/required image and try to use the placeholder=blur
  2. Notice no blur

Expected behavior
Blurred version of image

Desktop (please complete the following information):

  • OS: Win 10
  • Browser: Brave - Chromium
  • Version: latest

Allow extension/configuration in generation of custom-optimized-images.nd.json file

Is your feature request related to a problem? Please describe.
I have a blocker. My app loads images of different extensions from a DAM (digital asset management) system.

Currently this package determines the extension of the source image based on matched the src attribute of the image w/ a simple RegEx. If the URL ends in .jpg for example, then the determined format/extension is "jpg".

However, my image URLs don't fit this pattern. For example I have an image that I load with the route: "/file?id=someguid&variant=thumb&extension=jpg". The file is in jpg format but the src URL does not end in ".jpg".

These images don't get optimized currently using this package because the determined extension for this image is not "jpg" (the RegEx for determining the extension is not enough).

Describe the solution you'd like
Add a config option for "customFormatResolver" or some such. A function which takes the image src and any other possible attributes and returns a resolved format/extension so that the image is treated as a jpg for example even if the URL doesn't end in .jpg.

Describe alternatives you've considered
Looked for ways to rename my files to a format which would be processed/recognized by the package - its not an option if I want to load images directly from my DAM server.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): update dependency @testing-library/jest-dom to v6.4.2
  • chore(deps): update dependency @types/react to v18.2.55
  • chore(deps): update dependency postcss to v8.4.34
  • chore(deps): update dependency prettier to v3.2.5
  • chore(deps): update dependency @testing-library/react to v14.2.1
  • chore(deps): update dependency chokidar to v3.6.0
  • chore(deps): update typescript-eslint monorepo to v6.21.0 (@typescript-eslint/eslint-plugin, @typescript-eslint/parser)
  • chore(deps): update docusaurus monorepo to v3 (major) (@docusaurus/core, @docusaurus/preset-classic)
  • chore(deps): update github/codeql-action action to v3
  • chore(deps): update node.js to v20 (node, @types/node)
  • fix(deps): update dependency got to v14

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

asdf
.tool-versions
  • node 18.19.0
github-actions
.github/workflows/codeql-analysis.yml
  • actions/checkout v4
  • github/codeql-action v2
  • github/codeql-action v2
  • github/codeql-action v2
.github/workflows/node.js.yml
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/release.yml
  • actions/checkout v4
  • actions/setup-node v4
npm
docs/package.json
  • @docusaurus/core 2.4.3
  • @docusaurus/preset-classic 2.4.3
  • @heroicons/react 2.1.1
  • @mdx-js/react 1.6.22
  • autoprefixer 10.4.17
  • clsx 2.1.0
  • postcss 8.4.33
  • prettier 3.2.4
  • prettier-plugin-tailwindcss 0.5.11
  • prism-react-renderer 1.3.5
  • react 18.2.0
  • react-dom 18.2.0
  • tailwindcss 3.4.1
package.json
  • ansi-colors ^4.1.3
  • app-root-path ^3.1.0
  • cli-progress ^3.12.0
  • fs-extra ^11.2.0
  • got ^11.8.6
  • lodash.uniqwith ^4.5.0
  • recursive-readdir ^2.2.3
  • sharp ^0.32.6
  • @commitlint/cli 17.8.1
  • @commitlint/config-conventional 17.8.1
  • @semantic-release/changelog 6.0.3
  • @semantic-release/git 10.0.1
  • @testing-library/jest-dom 6.4.1
  • @testing-library/react 14.1.2
  • @tsconfig/strictest 2.0.2
  • @types/app-root-path 1.2.8
  • @types/benchmark 2.1.5
  • @types/cli-progress 3.11.5
  • @types/fs-extra 11.0.4
  • @types/jest 29.5.12
  • @types/lodash.uniqwith 4.5.9
  • @types/node 18.19.14
  • @types/react 18.2.52
  • @types/recursive-readdir ^2.2.4
  • @types/sharp 0.31.1
  • @typescript-eslint/eslint-plugin 6.19.1
  • @typescript-eslint/parser 6.19.1
  • benchmark 2.1.4
  • chokidar 3.5.3
  • conventional-changelog-conventionalcommits 7.0.2
  • cross-env 7.0.3
  • eslint 8.56.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-import 2.29.1
  • eslint-plugin-jest 27.6.3
  • eslint-plugin-jest-dom ^5.1.0
  • eslint-plugin-testing-library 5.11.1
  • git-cz 4.9.0
  • husky 8.0.3
  • jest 29.7.0
  • jest-environment-jsdom 29.7.0
  • lint-staged 13.3.0
  • next 13.4.19
  • npm-run-all 4.1.5
  • prettier 3.2.4
  • react 18.2.0
  • react-dom 18.2.0
  • rimraf 5.0.5
  • semantic-release 19.0.5
  • ts-jest 29.1.2
  • ts-node 10.9.2
  • tsup ^7.2.0
  • typescript 5.3.3
  • webpack 5.90.1
  • node 18.19.0
  • yarn 1.22.21

  • Check this box to trigger a request for Renovate to run again on this repository

Downloads can fail from filenames being too long

Describe the bug
When downloading external images, next-export-optimize-images can try to save images to files with names longer than what the file system allows for. This causes the whole program to fail.
Since URL Search parameters are included in the output filename, this can just happen from having several search parameters.

Most file systems seem to limit things to 255 characters or bytes (ex. btrfs does 255 bytes), so that would probably be a fine length limit.

To Reproduce
Steps to reproduce the behavior:

  1. Add an image with a really long filename to a project
  2. Build
  3. Export
  4. run next-export-optimize-images

Expected behavior
The images are downloaded, and the export continues

Screenshots
image

Desktop

  • OS: Linux

Cannot complete build

Describe the bug
A clear and concise description of what the bug is.

Hello, I was trying to use package to optimize my images. But after following the getting started guide and trying to build, I get the following error.

❯ npm run build                    

> [email protected] build
> next build

info - [next-export-optimize-images]: Configuration was not loaded. (This is optional.)
 ✓ Creating an optimized production build    
 ✓ Compiled successfully
 ✓ Linting and checking validity of types    
 ✓ Collecting page data    
   Generating static pages (0/5)  [=   ]TypeError: Cannot read properties of null (reading 'useContext')
    at exports.useContext (/tmp/test/node_modules/react/cjs/react.production.min.js:24:118)
    at /tmp/test/node_modules/next/dist/client/image-component.js:241:47
    at nh (/tmp/test/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:27:48668)
    at ny (/tmp/test/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:27:52524)
    at nf (/tmp/test/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:27:35987)
    at nh (/tmp/test/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:27:48675)
    at nh (/tmp/test/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:27:49347)
    at ny (/tmp/test/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:27:52524)
    at nv (/tmp/test/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:27:55162)
    at ng (/tmp/test/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:27:54569)

To Reproduce
Steps to reproduce the behavior:

  1. Create a new project.
❯ npx create-next-app@latest
Need to install the following packages:
[email protected]
Ok to proceed? (y) y
✔ What is your project named?test
✔ Would you like to use TypeScript? … No / **Yes**
✔ Would you like to use ESLint? … No / **Yes**
✔ Would you like to use Tailwind CSS? … No / **Yes**
✔ Would you like to use `src/` directory?**No** / Yes
✔ Would you like to use App Router? (recommended) … No / **Yes**
✔ Would you like to customize the default import alias (@/*)?**No** / Yes
Creating a new Next.js app in /tmp/test.

Using npm.
  1. Configure output for export
/** @type {import('next').NextConfig} */
const nextConfig = {
  output: "export",
};

module.exports = nextConfig;
  1. Run npm run build and observe succesful build
  2. Install the next-export-optimize-images package
  3. Modify next.config.js
const withExportImages = require("next-export-optimize-images");

/** @type {import('next').NextConfig} */
const nextConfig = withExportImages({
  output: "export",
});

module.exports = nextConfig;
  1. Try to build, you will see the error

Expected behavior

A successful build.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS] Linux/Ubuntu
  • Browser [e.g. chrome, safari] N/A
  • Version [e.g. 22] N/A

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6] N/A
  • OS: [e.g. iOS8.1] N/A
  • Browser [e.g. stock browser, safari] N/A
  • Version [e.g. 22] N/A

Additional context

I'm pretty new to next.js, been trying it for few days only, so it might be user error.
I didnt't see any other means to start a discussion, which is why I opened this bug report.

Thanks

site won't load images after export when export-images.config.js is not default

Node: v18.13.0
Next: 13.1.2
next-export-optimize-images: 2.0.0

  1. set something in export-images.config.js, fe.
/**
 * @type {import('next-export-optimize-images').Config}
 */
const config = {
  convertFormat: [
    ["png", "webp"],
    ["jpg", "avif"],
  ],
// or
  filenameGenerator: ({ path, name, width, quality, extension }) =>
    `${path}/${width}/${quality}/${name}.${extension}`,
};

module.exports = config;
  1. Run "export": "next build && next export && next-export-optimize-images"
  2. Run site via f.e. liveserver
  3. Check source of html file with images. srcSet is ok at this point
  4. Open devtools of same site with same images. srcSet are different so images images won't load when png was converted to webp ot filenameGenerator is custom.

Exits with errors if no <Image /> is present.

Describe the bug
A clear and concise description of what the bug is.
next-export-optimize-images fails if no is present

To Reproduce
Steps to reproduce the behavior:

  1. run create-next-app
  2. setup next-export-optimize-images according to documentation, including new export script
  3. clear index page so it is blank, remove all images from the project
  4. run "npm run export" or npx next-export-optimize-images
  5. See error

Expected behavior
Should not break build process but successfully optimize 0 / 0 assets

Desktop (please complete the following information):

  • OS: macOS arm64
  • Browser: Chrome
  • Version: any

Crypto browserify included in bundle: Around 130kB of JS added

Describe the bug
I think my fix in commit eae8c74 increased the bundle size because of crypto-browserify.

To Reproduce
Steps to reproduce the behavior:

  1. Analyze your bundle size with the package in version 1.9.1
  2. Remove the "withExportImages" plugin
  3. Re-analyze the bundle size

Expected behavior
There should be an impact but not that big. We don't need the full crypto package for a simple sha hash.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.