发布react项目出错,错误信息如下

2024-06-24T02:14:36.960Z [WARNING]: Error: Failed to launch chrome!
ERROR:zygote_host_impl_linux.cc(89)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.TROUBLESHOOTING:https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md
2024-06-24T02:14:36.976Z [WARNING]: error Command failed with exit code 1.
2024-06-24T02:14:36.976Z [INFO]: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
2024-06-24T02:14:36.981Z [ERROR]: !!! Build failed
2024-06-24T02:14:36.981Z [ERROR]: !!! Error: Command failed with exit code 1

出现了 Puppeteer 启动 Chrome 浏览器的问题,特别是与 root 用户权限有关。Puppeteer 不支持以 root 用户身份运行除非使用 --no-sandbox 参数。这在 CI/CD 环境中是常见的问题。

你可以在项目根目录下使用 npm ls puppeteer 命令来检查是否安装了 Puppeteer:

npm ls puppeteer

解决方案

  1. 添加 --no-sandbox 参数:
    在 Puppeteer 的启动选项中添加 --no-sandbox 参数。
  2. 使用非 root 用户:
    配置 CodeBuild 使用非 root 用户,但这可能需要更多的配置。
  3. 在package.json文件中删除Puppeteer以及依赖的包(不使用的情况下)

在 amplify.yml 中添加 --no-sandbox 参数
假设你的构建步骤中涉及到 Puppeteer,可以在启动 Puppeteer 的地方添加 --no-sandbox 参数。

修改 Puppeteer 配置

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  });
  // 其他代码
})();

更新 amplify.yml
确保你的 amplify.yml 文件中包含正确的安装和构建步骤。

version: 1
applications:
  - appRoot: . # 如果你的前端项目根目录是当前目录
    frontend:
      phases:
        preBuild:
          commands:
            - npm install # 或者 yarn install
        build:
          commands:
            - npm run build # 或者 yarn build
      artifacts:
        baseDirectory: build # 构建输出的目录,通常是build或dist
        files:
          - '**/*'
      cache:
        paths:
          - node_modules/**/*
    image: 'aws/codebuild/standard:5.0' # 使用最新的标准构建镜像

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐