通过 Dockerfile 编译时出现 TSC 错误



我有一个 Node/TypeScript 应用程序,我正在尝试从 Docker 运行它。

yarn tsc在本地工作正常,但在 Dockerfile 的上下文中不起作用。我认为问题在于使用 Dockerfile 从哪个目录运行命令,但我不确定如何解决它。

如何确保tsc可以看到tsconfig.json文件?

Dockerfile

FROM node:10
WORKDIR /usr/src/app
COPY package*.json ./
RUN yarn
# Copy source files.
COPY . .
# Run tsc.
RUN yarn prepare
# Run app.
CMD [ "yarn", "start" ]

包.json

"scripts": {
"prepare": "yarn tsc",
"tsc": "tsc -p .",
"dev": "ts-node-dev --respawn --transpileOnly server.ts",
"start": "./node_modules/nodemon/bin/nodemon.js ./build/server.js",
},

错误输出

docker build --tag app ./
Sending build context to Docker daemon  114.1MB
Step 1/7 : FROM node:10
---> e05cbde47b8f
Step 2/7 : WORKDIR /usr/src/app
---> Using cache
---> faaea91b16ae
Step 3/7 : COPY package*.json ./
---> 64310f50355d
Step 4/7 : RUN yarn
---> Running in be8aed305980
yarn install v1.16.0
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.9: The platform "linux" is incompatible with this module.
info "fsevents@1.2.9" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
$ yarn tsc
yarn run v1.16.0
$ tsc -p ./
error TS5057: Cannot find a tsconfig.json file at the specified directory: './'.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
The command '/bin/sh -c yarn' returned a non-zero code: 1

正如大卫所说,

仅仅运行 yarn

就相当于 yarn install,它运行一个"准备"脚本。

如果您不需要先运行 yarn 命令,则可以更改脚本以在运行 yarn 命令之前将应用程序代码复制到给定目录。

FROM node:10
WORKDIR /usr/src/app
# Copy source files.
COPY . .
RUN yarn
# Run app.
CMD [ "yarn", "start" ]

如果你仔细查看你的docker build输出,你会注意到运行的最后一个Dockerfile指令是

Step 4/7 : RUN yarn

特别是,yarn 将几个脚本名称视为特殊名称。 仅仅运行yarn就等效于yarn install,它运行一个"准备"脚本。 在您的情况下,"准备"脚本运行tsc;但是,这是在Dockerfile的"安装依赖项"阶段发生的,而您的应用程序代码尚未存在。

您可以使用纱线的--ignore-scripts选项来解决此问题。 在构建 Docker 映像的上下文中,许多其他选项在这里是有意义的。 (例如,可以使用多阶段生成来生成仅具有--production依赖项的最终映像,而不使用tsc编译器或其他生成时工具。

FROM node:10
WORKDIR /usr/src/app
COPY package.json yarn.lock ./
RUN yarn install --ignore-scripts --frozen-lockfile --non-interactive
COPY . .
RUN yarn prepare
CMD ["node", "./build/server.js"]

最新更新