Skip to content

Commit

Permalink
better image loader code (#17658)
Browse files Browse the repository at this point in the history
  • Loading branch information
maamokun authored and harshil1712 committed Dec 3, 2024
1 parent adce8bd commit bb08ac9
Showing 1 changed file with 24 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,30 +22,37 @@ To use Images with **all** your app's images, define a global [loaderFile](https

Add the following settings to the **next.config.js** file located at the root our your Next.js application.

```js
```ts
module.exports = {
images: {
loader: 'custom',
loaderFile: './imageLoader.js',
loaderFile: './imageLoader.ts',
},
}
```

Next, create the `imageLoader.js` file in the specified path (relative to the root of your Next.js application).
Next, create the `imageLoader.ts` file in the specified path (relative to the root of your Next.js application).

```js
const normalizeSrc = src => {
return src.startsWith('/') ? src.slice(1) : src;
```ts
const normalizeSrc = (src: string) => {
return src.startsWith("/") ? src.slice(1) : src;
};

export default function cloudflareLoader ({ src, width, quality }) {
const params = [`width=${width}`];
if (quality) {
params.push(`quality=${quality}`);
}
const paramsString = params.join(',');
return `/cdn-cgi/image/${paramsString}/${normalizeSrc(src)}`;
};
export default function cloudflareLoader({
src,
width,
quality,
}: { src: string; width: number; quality?: number }) {
if (process.env.NODE_ENV === "development") {
return src;
}
const params = [`width=${width}`];
if (quality) {
params.push(`quality=${quality}`);
}
const paramsString = params.join(",");
return `/cdn-cgi/image/${paramsString}/${normalizeSrc(src)}`;
}
```

### Custom Loaders
Expand All @@ -60,6 +67,9 @@ const normalizeSrc = src => {
};

const cloudflareLoader = ({ src, width, quality }) => {
if (process.env.NODE_ENV === "development") {
return src;
}
const params = [`width=${width}`];
if (quality) {
params.push(`quality=${quality}`);
Expand Down

0 comments on commit bb08ac9

Please sign in to comment.