From d2fba7852212d50e5a5cd03616010cc7139b79ae Mon Sep 17 00:00:00 2001 From: Wout De Puysseleir Date: Sat, 25 Mar 2023 13:50:58 -0700 Subject: [PATCH] Make it possible to disable SSR --- README.md | 18 ++++++++++++++++++ lib/component.ex | 9 +++++++-- lib/ssr.ex | 16 ++++++++++++++-- 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 70abf3b..f7484b2 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,7 @@ Svelte components need to go into the `assets/svelte` directory - Set the `name` of the Svelte component. - _Optional:_ Provide the `props` you want to use that should be reactive as a map to the props field - _Optional:_ Provide `class` to set the class attribute on the root svelte element +- _Optional:_ Set `ssr` to false to disable server-side rendering e.g. If your component is named `assets/svelte/Example.svelte`: @@ -222,6 +223,23 @@ e.g. Typescript cd assets && npm install --save-dev typescript ``` +### SSR + +SSR is enabled by default, but if you don't want to use Server-Side Rendering for Svelte, you can do 2 things: + +#### Globally + +If you don't want to use SSR on any component you can disable it globally. +This will automatically be the case if you don't include the `NodeJs` supervisor in you `application.ex` file + +#### Component + +To disable SSR on a specific component, set the `ssr` property to false. Like so: + +``` + +``` + ## Caveats ### Slot Interoperability diff --git a/lib/component.ex b/lib/component.ex index 0b4a9ba..3eace3c 100644 --- a/lib/component.ex +++ b/lib/component.ex @@ -8,6 +8,7 @@ defmodule LiveSvelte do attr(:props, :map, default: %{}) attr(:name, :string, required: true) attr(:class, :string, default: nil) + attr(:ssr, :boolean, default: true) slot(:inner_block) @@ -23,8 +24,12 @@ defmodule LiveSvelte do |> Slots.js_process() ssr_code = - if init do - SSR.render(assigns.name, Map.get(assigns, :props, %{}), slots) + if init and Map.get(assigns, :ssr) do + try do + SSR.render(assigns.name, Map.get(assigns, :props, %{}), slots) + rescue + SSR.NodeNotConfigured -> nil + end end assigns = diff --git a/lib/ssr.ex b/lib/ssr.ex index 905d00e..2b51be5 100644 --- a/lib/ssr.ex +++ b/lib/ssr.ex @@ -1,7 +1,19 @@ +defmodule LiveSvelte.SSR.NodeNotConfigured do + defexception message: """ + NodeJS is not configured. Please add the following to your application.ex: + {NodeJS.Supervisor, [path: "#{File.cwd!()}/assets", pool_size: 4]}, + """ +end + defmodule LiveSvelte.SSR do def render(name, props, slots \\ nil) def render(name, nil, slots), do: render(name, %{}, slots) - def render(name, props, slots), - do: NodeJS.call!({"js/render", "render"}, [name, props, slots]) + def render(name, props, slots) do + try do + NodeJS.call!({"js/render", "render"}, [name, props, slots]) + catch + :exit, {:noproc, _} -> raise LiveSvelte.SSR.NodeNotConfigured + end + end end