Skip to content

Commit

Permalink
fix: useContext API && add test case for prod
Browse files Browse the repository at this point in the history
  • Loading branch information
JuniorTour committed Feb 1, 2022
1 parent 64022e7 commit a4b790e
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 32 deletions.
20 changes: 16 additions & 4 deletions packages/next/client/image.tsx
@@ -1,13 +1,13 @@
import React, { useRef, useEffect } from 'react'
import React, { useRef, useEffect, useContext } from 'react'
import Head from '../shared/lib/head'
import {
ImageConfigComplete,
imageConfigDefault,
imageConfigRuntime,
LoaderValue,
VALID_LOADERS,
} from '../server/image-config'
import { useIntersection } from './use-intersection'
import { RuntimeImageConfigContext } from '../shared/lib/runtime-image-config-context'

const loadedImageURLs = new Set<string>()
const allImgs = new Map<
Expand Down Expand Up @@ -112,16 +112,26 @@ export type ImageProps = Omit<
onLoadingComplete?: OnLoadingComplete
}

const {
let {
deviceSizes: configDeviceSizes,
imageSizes: configImageSizes,
loader: configLoader,
path: configPath,
domains: configDomains,
} = (process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete) ||
imageConfigRuntime ||
imageConfigDefault

function setRuntimeImageConfig(imagesConfig: ImageConfigComplete) {
if (!imagesConfig || process.env.__NEXT_IMAGE_OPTS) return

// TODO robust solution for future
configDeviceSizes = imagesConfig.deviceSizes
configImageSizes = imagesConfig.imageSizes
configLoader = imagesConfig.loader
configPath = imagesConfig.path
configDomains = imagesConfig.domains
}

// sort smallest to largest
const allSizes = [...configDeviceSizes, ...configImageSizes]
configDeviceSizes.sort((a, b) => a - b)
Expand Down Expand Up @@ -392,6 +402,8 @@ export default function Image({
isLazy = false
}

setRuntimeImageConfig(useContext(RuntimeImageConfigContext))

if (process.env.NODE_ENV !== 'production') {
if (!src) {
throw new Error(
Expand Down
9 changes: 0 additions & 9 deletions packages/next/server/base-server.ts
Expand Up @@ -58,7 +58,6 @@ import { MIDDLEWARE_ROUTE } from '../lib/constants'
import { addRequestMeta, getRequestMeta } from './request-meta'
import { createHeaderRoute, createRedirectRoute } from './server-route-utils'
import { PrerenderManifest } from '../build'
import { ImageConfigComplete, setImageConfigRuntime } from './image-config'

export type FindComponentsResult = {
components: LoadComponentsReturnType
Expand Down Expand Up @@ -323,8 +322,6 @@ export default abstract class Server {
publicRuntimeConfig,
})

this.saveImageConfigRuntime(this.nextConfig.images)

this.pagesManifest = this.getPagesManifest()
this.middlewareManifest = this.getMiddlewareManifest()

Expand Down Expand Up @@ -1808,12 +1805,6 @@ export default abstract class Server {
protected get _isLikeServerless(): boolean {
return isTargetLikeServerless(this.nextConfig.target)
}

public saveImageConfigRuntime(
imageConfig: Partial<ImageConfigComplete>
): void {
setImageConfigRuntime(imageConfig)
}
}

export function prepareServerlessUrl(
Expand Down
10 changes: 0 additions & 10 deletions packages/next/server/image-config.ts
Expand Up @@ -33,13 +33,3 @@ export const imageConfigDefault: ImageConfigComplete = {
minimumCacheTTL: 60,
formats: ['image/webp'],
}

export let imageConfigRuntime: Partial<ImageConfigComplete> = imageConfigDefault

export function setImageConfigRuntime(
imageConfig: Partial<ImageConfigComplete>
) {
if (imageConfig) {
imageConfigRuntime = imageConfig
}
}
9 changes: 8 additions & 1 deletion packages/next/server/render.tsx
Expand Up @@ -63,6 +63,7 @@ import { DomainLocale } from './config'
import RenderResult, { NodeWritablePiper } from './render-result'
import isError from '../lib/is-error'
import { readableStreamTee } from './web/utils'
import { RuntimeImageConfigContext } from '../shared/lib/runtime-image-config-context'

let Writable: typeof import('stream').Writable
let Buffer: typeof import('buffer').Buffer
Expand Down Expand Up @@ -237,6 +238,7 @@ export type RenderOptsPartial = {
serverComponents?: boolean
customServer?: boolean
crossOrigin?: string
images: string
}

export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
Expand Down Expand Up @@ -447,6 +449,7 @@ export async function renderToHTML(
devOnlyCacheBusterQueryString,
supportsDynamicHTML,
concurrentFeatures,
images,
} = renderOpts

const isServerComponent = !!serverComponentManifest
Expand Down Expand Up @@ -718,7 +721,11 @@ export async function renderToHTML(
value={(moduleName) => reactLoadableModules.push(moduleName)}
>
<StyleRegistry registry={jsxStyleRegistry}>
{children}
<RuntimeImageConfigContext.Provider
value={images ? JSON.parse(images) : null}
>
{children}
</RuntimeImageConfigContext.Provider>
</StyleRegistry>
</LoadableContext.Provider>
</HeadManagerContext.Provider>
Expand Down
12 changes: 12 additions & 0 deletions packages/next/shared/lib/runtime-image-config-context.ts
@@ -0,0 +1,12 @@
import React from 'react'
import {
ImageConfigComplete,
imageConfigDefault,
} from '../../server/image-config'

export const RuntimeImageConfigContext =
React.createContext<ImageConfigComplete>(imageConfigDefault)

if (process.env.NODE_ENV !== 'production') {
RuntimeImageConfigContext.displayName = 'RuntimeImageConfigContext'
}
@@ -1,5 +1,11 @@
/* eslint-env jest */
import { findPort, killApp, launchApp } from 'next-test-utils'
import {
killApp,
findPort,
nextStart,
nextBuild,
launchApp,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'

Expand All @@ -8,7 +14,29 @@ let appPort
let app
let browser

// #31065
function runTests() {
// #31065
it('should apply image config for node_modules', async () => {
browser = await webdriver(appPort, '/image-from-node-modules')
expect(
await browser.elementById('image-from-node-modules').getAttribute('src')
).toMatch('i.imgur.com')
})
}

describe('Image Component Tests In Prod Mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
})

runTests()
})

describe('Image Component Tests In Dev Mode', () => {
beforeAll(async () => {
appPort = await findPort()
Expand All @@ -18,10 +46,5 @@ describe('Image Component Tests In Dev Mode', () => {
await killApp(app)
})

it('should apply image config for node_modules', async () => {
browser = await webdriver(appPort, '/image-from-node-modules')
expect(
await browser.elementById('image-from-node-modules').getAttribute('src')
).toMatch('i.imgur.com')
})
runTests()
})

0 comments on commit a4b790e

Please sign in to comment.