在 Elixir/Phoenix 中重用 nuxt 代码

reusing nuxt codes in Elixir/Phoenix

背景

我一直在用 nuxt 构建前端,elixir/phoenix 作为后端,用 nginx 作为反向代理。

但是,为了提高性能,我想在 Elixir/Phoenix 中部署整个东西。

我的Objective

我想在Elixir/Phoenix中使用我的nuxt代码。

不明白的地方

我不知道如何保留在 nuxt.config.js 中进行的路由、服务器端渲染和配置。 尽管如果我保留了我让它可以在全球范围内访问的组件,我可以放弃其他配置。

如果你想在生产中使用它,那就不要! :).在我看来,不值得让凤凰应用负责node.js个应用。但是,如果您想 运行 在开发过程中将所有这些作为单个 mix phx.server 命令,请按照以下步骤操作。

创建 GenServer 将启动 nuxt 应用程序并将该 genserver 添加到应用程序监督树。 assets_path 应该是你的 nuxt app package.json 文件所在的路径,这个 assets_path 不必在你的 phoenix app


    defmodule NuxtServer do
      use GenServer, restart: :permanent
      require Logger

      def start_link(assets_path, opts \ []) do
        GenServer.start(\__MODULE__, [assets_path], opts)
      end

      def init([assets_path]) do
        # in assets folder package.json should contain under scripts node
        # scripts: {
        #   ...
        #   "nuxt": "nuxt"
        # }
        port = Port.open({:spawn, "npm run nuxt"}, [{:cd, assets_path}])
        ref = Port.monitor(port)
        {:ok, %{port: port, ref: ref, assets_path: assets_path}}
      end

      def handle_info({:DOWN, _, :port, _, _}, %{assets_path: assets_path, ref: ref, port: port}) do
        Logger.error("Nuxt server is down, restarting ...")

        Port.close(port)

        Port.demonitor(ref)
        {:ok, state} = init([assets_path])
        {:noreply, state}
      end

      def handle_info({_prot, {:data, msg}}, s) do
        Logger.debug msg
        {:noreply, s}
      end

      def handle_info(msg, state), do: super(msg, state)
    end

然后按照说明如何使用例如在 phoenix 中添加反向代理lib 如果您需要通过 phoenix http 端口访问所有内容。