瀏覽代碼

Fix Nextjs Dynamic Import (#1480)

* Fix dunamic imoprt for react player and plotly

* Fix format

* Fix pr comments

* Update react player

---------

Co-authored-by: Alek Petuskey <alekpetuskey@aleks-mbp.lan>
Alek Petuskey 1 年之前
父節點
當前提交
b9536bcf40
共有 3 個文件被更改,包括 15 次插入25 次删除
  1. 10 0
      reflex/components/component.py
  2. 2 10
      reflex/components/graphing/plotly.py
  3. 3 15
      reflex/components/libs/react_player.py

+ 10 - 0
reflex/components/component.py

@@ -777,3 +777,13 @@ def custom_component(
         return CustomComponent(component_fn=component_fn, children=children, **props)
 
     return wrapper
+
+
+class NoSSRComponent(Component):
+    """A dynamic component that is not rendered on the server."""
+
+    def _get_imports(self):
+        return {"next/dynamic": {ImportVar(tag="dynamic", is_default=True)}}
+
+    def _get_custom_code(self) -> str:
+        return f"const {self.tag} = dynamic(() => import('{self.library}'), {{ ssr: false }});"

+ 2 - 10
reflex/components/graphing/plotly.py

@@ -4,12 +4,12 @@ from typing import Dict
 
 from plotly.graph_objects import Figure
 
-from reflex.components.component import Component
+from reflex.components.component import NoSSRComponent
 from reflex.components.tags import Tag
 from reflex.vars import Var
 
 
-class PlotlyLib(Component):
+class PlotlyLib(NoSSRComponent):
     """A component that wraps a plotly lib."""
 
     library = "react-plotly.js"
@@ -35,14 +35,6 @@ class Plotly(PlotlyLib):
     # If true, the graph will resize when the window is resized.
     use_resize_handler: Var[bool]
 
-    def _get_imports(self):
-        return {}
-
-    def _get_custom_code(self) -> str:
-        return """import dynamic from 'next/dynamic'
-const Plot = dynamic(() => import('react-plotly.js'), { ssr: false });
-"""
-
     def _render(self) -> Tag:
         if (
             isinstance(self.data, Figure)

+ 3 - 15
reflex/components/libs/react_player.py

@@ -2,19 +2,16 @@
 
 from __future__ import annotations
 
-from typing import Optional
-
-from reflex.components.component import Component
-from reflex.utils import imports
+from reflex.components.component import NoSSRComponent
 from reflex.vars import Var
 
 
-class ReactPlayerComponent(Component):
+class ReactPlayerComponent(NoSSRComponent):
     """Using react-player and not implement all props and callback yet.
     reference: https://github.com/cookpete/react-player.
     """
 
-    library = "react-player"
+    library = "react-player/lazy"
 
     tag = "ReactPlayer"
 
@@ -44,12 +41,3 @@ class ReactPlayerComponent(Component):
 
     # Set the height of the player: ex:640px
     height: Var[str]
-
-    def _get_imports(self) -> Optional[imports.ImportDict]:
-        return {}
-
-    def _get_custom_code(self) -> Optional[str]:
-        return """
-import dynamic from "next/dynamic";
-const ReactPlayer = dynamic(() => import("react-player/lazy"), { ssr: false });
-"""