如何在Dockerfile中编译打字稿

Tie*_*eDK 5 node.js typescript docker

我无法从Dockerfile编译nodejs打字稿应用程序。当我构建泊坞窗映像时,检查将其完全丢失dist文件夹。

Dockerfile:

# Template: Node.js dockerfile
# Description: Include this file in the root of the application to build a docker image.

# Enter which node build should be used. E.g.: node:argon 
FROM node:latest

# Create app directory for the docker image
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app/dist

# Install app dependencies from package.json. If modules are not included in the package.json file enter a RUN command. E.g. RUN npm install <module-name>
COPY package.json /usr/src/app/
RUN     npm install
RUN     npm install tsc -g
RUN     tsc

# Bundle app source
COPY . /usr/src/app

# Enter the command which should be used when the image starts up. E.g. CMD ["node", "app.js"]
CMD [ "node", "server.js"]
Run Code Online (Sandbox Code Playgroud)

当我在本地运行映像并通过ls显示文件/文件夹时:

# ls
node_modules  package-lock.json  package.json  src
Run Code Online (Sandbox Code Playgroud)

任何建议,我要去哪里错了?

Max*_*Max 10

正如我据我所知,
WORKDIR不必由自己创造。这是WORKDIR文档

之后您不必手动复制到特定文件夹,因为在WORKDIR命令之后复制命令将为您复制文件。

因此,我建议您使用以下 Dockerfile:

    FROM node:alpine
    WORKDIR /usr/yourapplication-name
    COPY package.json .
    RUN npm install\
        && npm install typescript -g
    COPY . .
    RUN tsc
    CMD ["node", "./dist/server.js"]
Run Code Online (Sandbox Code Playgroud)

作为一个小技巧:我会使用 typescript 作为我的依赖项package.json,然后只使用以下文件:

    FROM node:alpine
    WORKDIR /usr/yourapplication-name
    COPY package.json .
    RUN npm install
    COPY . .
    RUN tsc
    CMD ["node", "./dist/server.js"]
Run Code Online (Sandbox Code Playgroud)

  • 后者返回:`/bin/sh: 1: tsc: not find`。 (5认同)
  • @DerkJanSpeelman:因为打字稿必须是您的项目的依赖项(正如我在回答中所写)。然后 npm install 将安装项目的所有依赖项,并且将找到命令 tsc (3认同)