Skip to content

Commit

Permalink
fix: 🐛 Removed crypto dependency from client bundle
Browse files Browse the repository at this point in the history
Uses hashCode instead of sha1 for external images

✅Closes: #332
  • Loading branch information
Gp2mv3 committed Dec 8, 2022
1 parent 7569362 commit ca4ea71
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
4 changes: 2 additions & 2 deletions __tests__/components/image/external-images/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,15 @@ describe('External images', () => {
externalUrl: 'https://next-export-optimize-images.vercel.app/sub-path/og.png',
output: '/_next/static/chunks/images/sub-path/og_1920_75.webp',
quality: 75,
src: '/_next/static/media/8fcb025d6e036ec05907f2367ee713067a0c406c.png',
src: '/_next/static/media/-803215824.png',
width: 1920,
},
{
extension: 'webp',
externalUrl: 'https://next-export-optimize-images.vercel.app/sub-path/og.png',
output: '/_next/static/chunks/images/sub-path/og_3840_75.webp',
quality: 75,
src: '/_next/static/media/8fcb025d6e036ec05907f2367ee713067a0c406c.png',
src: '/_next/static/media/-803215824.png',
width: 3840,
},
])
Expand Down
28 changes: 17 additions & 11 deletions src/image.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import { createHash } from 'crypto'

import Image, { ImageLoader, ImageProps } from 'next/dist/client/image'
import React from 'react'

Expand All @@ -10,6 +8,16 @@ import getConfig, { ParsedImageInfo } from './utils/getConfig'

const config = getConfig()

function hashCode(src: string) {
let hash = 0
for (let i = 0; i < src.length; i += 1) {
const chr = src.charCodeAt(i)
hash = (hash << 5) - hash + chr
hash |= 0 // Convert to 32bit integer
}
return `${hash}`
}

const defaultImageParser: (src: string) => ParsedImageInfo = (src: string) => {
const path = src.split(/\.([^.]*$)/)[0]
const extension = (src.split(/\.([^.]*$)/)[1] || '').split('?')[0]
Expand Down Expand Up @@ -86,15 +94,13 @@ const exportableLoader: ImageLoader = ({ src: _src, width, quality }) => {
const path = require('path') as typeof import('path')

if (src.startsWith('http')) {
json.src = `/${externalOutputDir}/${createHash('sha1')
.update(
src
.replace(/^https?:\/\//, '')
.split('/')
.slice(1)
.join('/')
)
.digest('hex')}.${originalExtension}`
json.src = `/${externalOutputDir}/${hashCode(
src
.replace(/^https?:\/\//, '')
.split('/')
.slice(1)
.join('/')
)}.${originalExtension}`

json.externalUrl = src
}
Expand Down

0 comments on commit ca4ea71

Please sign in to comment.