Skip to content

Commit

Permalink
fix: ensure VisualEditing isn't added to the server bundle
Browse files Browse the repository at this point in the history
  • Loading branch information
nkgentile committed May 20, 2024
1 parent b5c6d38 commit ba3d3e6
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
16 changes: 16 additions & 0 deletions src/visual-editing/VisualEditing.client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {VisualEditing} from '@sanity/visual-editing/remix'

/**
* Prevent a consumer from importing into a worker/server bundle.
*/
if (typeof document === 'undefined') {
throw new Error(
'Visual editing should only run client-side. Please check that this file is not being imported into a worker or server bundle.',
)
}

/**
* Enables visual editing on the front-end
* @see https://www.sanity.io/docs/introduction-to-visual-editing
*/
export default VisualEditing
27 changes: 21 additions & 6 deletions src/visual-editing/VisualEditing.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,32 @@
import type {VisualEditingProps} from '@sanity/visual-editing/remix'
import {lazy, type ReactElement, Suspense} from 'react'

const VisualEditingComponent = lazy(() =>
import('@sanity/visual-editing/remix').then((mod) => ({default: mod.VisualEditing})),
)
/**
* Provide a consistent fallback to prevent hydration mismatch errors.
*/
function VisualEditingFallback(): ReactElement {
return <></>
}

/**
* Enables visual editing on the front-end
* @see https://www.sanity.io/docs/introduction-to-visual-editing
* If server-side rendering, then return the fallback instead of the heavy dependency.
* @see https://remix.run/docs/en/1.14.3/guides/constraints#browser-only-code-on-the-server
*/
const VisualEditingComponent =
typeof document === 'undefined'
? VisualEditingFallback
: lazy(
() =>
/**
* `lazy` expects the component as the default export
* @see https://react.dev/reference/react/lazy
*/
import('./VisualEditing.client'),
)

export function VisualEditing(props: VisualEditingProps): ReactElement {
return (
<Suspense fallback={null}>
<Suspense>
<VisualEditingComponent {...props} />
</Suspense>
)
Expand Down

0 comments on commit ba3d3e6

Please sign in to comment.