Firebase CLI: "将其配置为单页应用程序(将所有URL重写为/index.html)"

85

我刚刚使用 Firebase CLI 初始化了一个静态托管项目。当启用“配置为单页应用程序”选项时会发生什么?我正在寻找有关修改哪些文件以及这对 Firebase 后端产生何种影响的详细描述。

Firebase init 命令截图


我不熟悉那个选项。你能展示一下在哪里启用它或者它在哪里有文档吗? - Frank van Puffelen
2
@FrankvanPuffelen,请查看我在问题中添加的截图。 - Kayce Basques
5个回答

118

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

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

请查看Firebase Hosting文档以获取更多信息,其中还包含此更完整的示例:https://firebase.google.com/docs/hosting/full-config#rewrites
"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"
  } ]
}

2
使用此配置 http://localhost:5000/qqq 可以渲染,但是 http://localhost:5000/qqq/www 却无法渲染,我该如何解决这个问题?第二个链接无法呈现 index.html。 - Teoman shipahi
1
我们如何在这里编写API/函数呢?例如:'somewebsite.com/api',它将重定向到一个函数,但也具有根网站somewebsite.com,使用** - Oliver Dixon
1
谢谢提醒。我添加了来自链接文档的更完整示例,以帮助减少风险。 - Frank van Puffelen
1
如果您正在使用React,则可以通过使用React Router作为路由系统,使JS按预期重定向到每个路由。 - Mars2024

30

完整示例:

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

20

如果您将其设置为“是”,则所有无效的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,以从已部署的网站URL中删除.html扩展名,否则所有没有.html的网址将重定向到index.html


5
作为注释:如果您想要进行服务器端渲染(SSR),请键入No 并按照以下方式设置您的rewrites
"rewrites": [
  {
    "function": "angularUniversalFunction",
    "source": "**"
  }
]

无论你选择哪种方式,你都可以在 firebase.json 文件中随时进行更改。

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接