反应脚本:在 CI 中构建 docker 图像时未找到,但在本地工作

react-scripts: not found when building docker image in CI, but works locally

我有一个 Dockerfile 来构建 React 应用程序并将构建复制到 Nginx 容器。

FROM node:14-buster-slim AS node-base

FROM node-base as deps
WORKDIR /app

COPY ./ui/package.json ./ui/yarn.lock ./ui/.npmrc ./
RUN yarn install --frozen-lockfile

FROM node-base as build-ui
WORKDIR /app

COPY ./ui ./
COPY --from=deps /app/package.json /app/yarn.lock /app/node_modules ./
RUN yarn run build

FROM nginx:1.21-alpine as ui-server
WORKDIR /usr/share/nginx/html

COPY --from=build-ui /app/build .

COPY ./ui/nginx/nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 80

在本地,构建工作没有问题。然而,在 CI 中,它无法构建:

#14 [build-ui 4/4] RUN yarn run build
#14 0.490 yarn run v1.22.17
#14 0.523 $ react-scripts build
#14 0.535 /bin/sh: 1: react-scripts: not found
#14 0.545 error Command failed with exit code 127.
#14 0.546 info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
#14 ERROR: process "/bin/sh -c yarn run build" did not complete successfully: exit code: 127

它在本地工作的原因是因为我的本地 node_modulesCOPY ./ui ./ 步骤中被复制到容器中。

一旦我 .dockerignore-d node_modules,意识到 COPY --from=deps /app/package.json /app/yarn.lock /app/node_modules ./ 正在将 node_modules 的子项复制到项目根目录而不是模块目录。

将 COPY 步骤更改为以下步骤解决了问题:

COPY --from=deps /app/package.json /app/yarn.lock ./
COPY --from=deps /app/node_modules /app/node_modules