Skip to content

Commit

Permalink
fix(plugin): create static manifest for client hydration (#162)
Browse files Browse the repository at this point in the history
  • Loading branch information
farnabaz authored Jan 26, 2021
1 parent 7a0042a commit 0b10c22
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/runtime/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ import { hasProtocol, joinURL } from 'ufo'
import type { ImageOptions, CreateImageOptions, ResolvedImage, MapToStatic, ImageCTX } from '../types/image'
import { imageMeta } from './utils/meta'
import { parseSize } from './utils'
import { useStaticImageMap } from './utils/static-map'

export function createImage (globalOptions: CreateImageOptions, nuxtContext) {
const staticImageManifest = (process.client && process.static) ? useStaticImageMap(nuxtContext) : {}

const ctx: ImageCTX = {
options: globalOptions,
allow: allowList(globalOptions.allow),
Expand All @@ -24,8 +27,8 @@ export function createImage (globalOptions: CreateImageOptions, nuxtContext) {
const staticImagesBase = '/_nuxt/image' // TODO

if (process.client && 'fetchPayload' in window.$nuxt) {
const mappedURL = (window.$nuxt as any)?._pagePayload?.pagePayload?.data?.[0]?._img[image.url]
image.url = mappedURL || input
const mappedURL = staticImageManifest[image.url]
image.url = mappedURL ? joinURL(staticImagesBase, mappedURL) : input
return image
}

Expand Down
26 changes: 26 additions & 0 deletions src/runtime/utils/static-map.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const staticImageMap = {}

function updateImageMap () {
if (typeof window.$nuxt !== 'undefined') {
const pageImages = (window.$nuxt as any)._pagePayload?.data?.[0]?._img || {}
Object.assign(staticImageMap, pageImages)
console.log(staticImageMap)
}
}

export function useStaticImageMap (nuxtContext?) {
// Update on initialization
updateImageMap()

// Merge new mappings on route change
if (nuxtContext) {
nuxtContext.app.router.afterEach(updateImageMap)
}

// Make sure manifest is initialized
if ((window as any).onNuxtReady) {
(window as any).onNuxtReady(updateImageMap)
}

return staticImageMap
}

0 comments on commit 0b10c22

Please sign in to comment.