View Source PlugLiveReload.Socket (plug_live_reload v0.2.0)

Cowboy socket handler that sends websocket events. This websocket is what the PlugLiveReload plug's injected Javascript subscribes to in order to know when to reload.

Usage

Add the PlugLiveReload.Socket to your Plug.Cowboy child spec.

  def start(_type, _args) do
    children = [
      {Plug.Cowboy, scheme: :http, plug: MyApp.Router, options: [
        port: 4000,
        dispatch: dispatch()
      ]}
    ]

    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    Supervisor.start_link(children, opts)
  end

  if Mix.env() == :dev do
    def dispatch(),
      do: [
        {:_,
        [
          {"/plug_live_reload/socket", PlugLiveReload.Socket, []},
          {:_, Plug.Cowboy.Handler, {MyApp.Router, []}}
        ]}
      ]
  else
    def dispatch(), do: nil
  end

This adds a new :cowboy_websocket handler for one route, /plug_live_reload/socket. All other routes will continue to be handled as usual by your plug router. This also makes it so that handler is not added at all in the :dev environment.

Configuration

This socket will only send events informing the page to reload if it the path of the changed resource matches any of the configured :patterns.

  config :plug_live_reload,
    patterns: [
      ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
    ]

The configuration above will send an event if any of the JS/CSS/etc files in the priv/static change.