React 使用 npm 部署到 AWS S3 生产 - 最后是 index.html 文件

问题描述 投票:0回答:3

我有一个 React 应用程序(使用 React Create App),我想使用脚本将其上传到生产环境。我的产品是 AWS S3 存储桶。我已向 package.json 添加了一个“部署”脚本,如下所示:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "deploy": "aws s3 cp ./build s3://app.example.com --recursive --exclude \"*.DS_Store\" --cache-control public,max-age=604800 --profile production-profile"
  },

这会将所有构建文件上传到生产存储桶。由于构建静态文件(css、js 等)有自己的哈希码,因此它们不会被每个版本覆盖,这很好。

我遇到的问题是,在其他文件完成上传之前,我不希望上传index.html 文件。这样,一旦使用最新版本覆盖 index.html,就会自动使用新的静态文件。

知道如何实现这一目标吗?如果有更好的脚本将 React 应用程序上传到 S3 那就太好了。

javascript reactjs amazon-s3 webpack create-react-app
3个回答
6
投票

您可以先复制除index.html之外的其他所有内容,然后再复制它。

 "aws s3 cp ./build s3://app.example.com --recursive --exclude \"*.DS_Store\" --exclude \"index.html\" --cache-control public,max-age=604800 --profile production-profile && aws s3 cp ./build/index.html s3://app.example.com  --cache-control public,max-age=604800 --profile production-profile "

1
投票

如果我没记错的话,您希望index.html 文件最后上传,以便它将包含应在您的应用程序中加载的静态js/css 文件名(旧的index.html 包含旧版本),对吧?

那么您可以做的是让 s3 删除正在上传的文件中不存在的文件:

aws s3 sync build/ s3://app.example.com --delete --exclude \"*.DS_Store\" --cache-control public,max-age=604800 --profile production-profile

该命令“同步目录和 S3 前缀。将新文件和更新的文件从源目录递归复制到目标目录。仅在目标目录中创建包含一个或多个文件的文件夹。” - AWS 文档

“--delete 标志将导致 CLI 删除目标中而非源中的文件。” - AWS 帮助

因此,这仍然应该上传构建目录中的所有内容,但也会删除旧版本的文件。

编辑(而不是删除旧文件):

# Exclude the index.html file for first upload, you could probably use cp instead of sync
aws s3 sync build/ s3://app.example.com --exclude \"*.DS_Store\" --exclude "index.html" --cache-control public,max-age=604800 --profile production-profile
# Add it after everything else is uploaded
aws s3 sync build/index.html s3://app.example.com --exclude \"*.DS_Store\" --cache-control public,max-age=604800 --profile production-profile

0
投票

有一种便捷的方式将 SPA 部署到 S3 和 CloudFront,并轻松在云上设置基础设施! 它称为 SWS Console Quick Cloud Architecture Builder 服务。只需几个简单的输入,您就可以控制 AWS 资源。请参阅下面的文档!

使用 SWS 控制台快速云架构构建器使前端部署变得简单

使用 S3 和 CloudFront 将 SPA(React、Vue 等)项目部署到 AWS 时,需要执行一些复杂的任务,例如在 S3 上设置静态 Web 托管并将存储桶链接到 CloudFront。不如使用 Sws Console 服务,它为您的 SPA 项目构建 S3 静态 Web 托管 + CloudFront 的 AWS 云架构,而无需担心这些任务?请参考下面的文档,尝试使用Sws Console Quick Builder工具快速构建AWS架构!

使用 SWS 控制台快速云架构构建器使前端部署变得简单

进入Sws控制台服务页面

© www.soinside.com 2019 - 2024. All rights reserved.