From ba3d3e6608b3f32e9769883610e49d00caeed71f Mon Sep 17 00:00:00 2001 From: Noah Gentile Date: Mon, 20 May 2024 11:43:52 -0700 Subject: [PATCH] fix: ensure `VisualEditing` isn't added to the server bundle --- src/visual-editing/VisualEditing.client.tsx | 16 ++++++++++++ src/visual-editing/VisualEditing.tsx | 27 ++++++++++++++++----- 2 files changed, 37 insertions(+), 6 deletions(-) create mode 100644 src/visual-editing/VisualEditing.client.tsx diff --git a/src/visual-editing/VisualEditing.client.tsx b/src/visual-editing/VisualEditing.client.tsx new file mode 100644 index 0000000..4c0f7d6 --- /dev/null +++ b/src/visual-editing/VisualEditing.client.tsx @@ -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 diff --git a/src/visual-editing/VisualEditing.tsx b/src/visual-editing/VisualEditing.tsx index 1f9623f..e9573e1 100644 --- a/src/visual-editing/VisualEditing.tsx +++ b/src/visual-editing/VisualEditing.tsx @@ -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 ( - + )