Firebase CLI:"Configure as a single-page app (rewrite all urls to /index.html)"

Firebase CLI: "Configure as a single-page app (rewrite all urls to /index.html)"

我刚刚使用 Firebase CLI 初始化了一个静态托管项目。当您启用 "configure as a single-page app" 选项时究竟会发生什么?我正在寻找对哪些文件被修改的确切描述,以及这对 Firebase 后端有什么样的影响。

该选项只是在 firebase.json 文件中设置一个标志,将所有 URL 重定向到 /index.html

"rewrites": [ {
  "source": "**",
  "destination": "/index.html"
} ]

有关详细信息,请参阅 documentation of Firebase Hosting,其中还包含这个更完整的示例:

"hosting": {
  // ...

 // Add the "rewrites" attribute within "hosting"
  "rewrites": [ {
    // Serves index.html for requests to files or directories that do not exist
    "source": "**",
    "destination": "/index.html"
  }, {
    // Serves index.html for requests to both "/foo" and "/foo/**"
    // Using "/foo/**" only matches paths like "/foo/xyz", but not "/foo"
    "source": "/foo{,/**}",
    "destination": "/index.html"
  }, {
    // Excludes specified pathways from rewrites
    "source": "!/@(js|css)/**",
    "destination": "/index.html"
  } ]
}

完整示例:

{
  "hosting": {
    "public": ".",
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

Firebase 官方解释:

我们去年(Q1 和 Q2)使用过这个选项,但它似乎什么也没做,但现在当我们应用它时,事情肯定会大不相同。 其作用的完整官方解释在这里:

https://firebase.google.com/docs/hosting/url-redirects-rewrites#section-rewrites

在同一页面的下一部分甚至还有一些关于 Headers 用法的有用信息。

注意:如果您想要服务器端呈现 (SSR),请输入 No 并按如下方式设置您的 rewrites

"rewrites": [
  {
    "function": "angularUniversalFunction",
    "source": "**"
  }
]

毕竟,无论您选择什么,都可以随时在 firebase.json 文件中进行更改。

如果您将其设置为是,那么所有无效的 URL,如 www.example.com/some-invalid-url 将被重定向到您网站的 index.html,这是一件好事。您也可以将其设置为您的自定义 404.html.

firebase.json

{

  "hosting": {
    "public": "pubic",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ],
    "cleanUrls": true
  }
}

奖励:将 cleanUrls 设置为 true 以从已部署的网站网址中删除 .html 扩展名,否则所有不带 .html 的网址都将重定向到 index.html .