如何将 React 应用程序的生产 npm 构建部署到 Azure 应用服务

IT技术 javascript reactjs azure azure-web-app-service create-react-app
2021-05-08 07:20:30

我正在尝试通过 ftp 将我的 React 应用程序的 npm 构建版本部署到 azure Web 服务。我移动了构建文件夹,但是当我加载应用程序的 URL 时,默认屏幕加载了Hey Node Developers!.

我可以通过 github 和 kudu 进行部署。不过,我不相信这是一个生产质量的应用,因为它不使用内置npm run buildcreate-react-app

我已经阅读了这个 azure guide以及各种博客。我也包含了该web.config文件。没有什么可以让我的页面正确加载。

我已经使用节点版本尝试10.110.14LTS我曾尝试同时使用 Linux 和 Windows 应用服务。

2个回答

由于 Linux Azure Web Apps 使用 pm2 为节点应用程序提供服务,因此您需要配置Azure Linux Web App Service以在“设置>常规设置>启动命令”中运行启动命令来为您的 React 应用程序提供服务

pm2 serve /home/site/wwwroot/ --no-daemon

请记住更改构建路径的路径(您的 index.html 文件的路径)。

如果您使用 react-router 并希望通过 index.html 处理对自定义路由的任何直接访问,则需要--spa在同一命令上添加选项。

pm2 serve /home/site/wwwroot/ --no-daemon --spa

使用--spa选项 pm2 将自动将所有查询重定向到 index.html,然后react-router将发挥其魔力。

您可以在 pm2 文档中找到有关它的更多信息:https ://pm2.keymetrics.io/docs/usage/pm2-doc-single-page/#serving-spa-redirect-all-to-indexhtml

我最近解决了同样的问题:React router direct links not working on Azure Web App Linux

适用于 Windows 的 Azure 应用服务(Node JS)

本地 Git 上传到 Azure 应用服务

  1. 在 Azure 门户中打开您的应用服务Deployment>> Deployment Center- 如果您已经设置了部署选项,则必须按Disconnect
  2. 选择Local Git> App Service Build Service> Summary>Finish
  3. 选择 FTP/凭据(在左上角)> 选择用户凭据 - 设置密码并保存凭据
  4. 返回概览,使用您的 git 用户名复制 git 部署 URL。应该是这样的格式:https://<user_name>@<app_service_name>.scm.azurewebsites.net:443/<app_service_name>.git
  5. npm run build从您机器上本地的项目文件夹运行
  6. 完成构建后./build运行git init以初始化您的 git repo
  7. 运行git remote add azure https://<user_name>@<app_service_name>.scm.azurewebsites.net:443/<app_service_name>.git以添加 Azure 部署作为推送到的选项
  8. 运行git add *git commit -m "${date}"git push azure master:master
  9. 系统会提示您输入密码。它将是您在 FTP/凭据屏幕上时提供的密码。
  10. 测试您的网站。它应该可以在https://<app_service_name.azurewebsites.net

如果您希望将来将更新推送到您的应用服务,您只需执行第 8 步到第 10 步。

为 React-Router 配置 IIS

react-router与您的 React SPA 一起使用,您还需要配置 Web 应用程序以将 404 错误重新路由到index.html. 您可以通过在/site/wwwroot/名为web.config. 放置下面的内容并从 Azure 门户重新启动应用服务。

<?xml version="1.0"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="React Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>