northsideknight
northsideknight

Reputation: 1557

How to transpile typescript to javascript on Docker volume?

I have a Typescript node application. The main file is server.ts. I want to run this application in a Docker container. I have a build step in my Dockerfile that runs the Typescript transpilation, example:

FROM node:9.9 as build

WORKDIR /app

COPY package*.json ./
COPY ... # copy the source files to the docker container 

RUN npm install && \
npm run build  # <-- runs Typescript transpile

FROM node:9.9

COPY --from=build /path/to/source/files /app

WORKDIR /path/to/server.js directory

CMD ["node", "server.js"]

I use docker-compose to configure the container for development

my-app:
  build:
    context: /path/to/build/context
    dockerfile: Dockerfile
  command: bash -c "npm install -g nodemon && nodemon server.js"
  network_mode: "host"
  volumes:
    - /path/to/server.js/directory/local:/path/to/server.js/directory/in/container

Since the Typescript is transpiled during the image build phase, the server.js file is created within the container. So if I run docker-compose without the volumes included, the server.js file is there and the container starts fine. If I run docker-compose with the volumes, the server.js file is not there, just server.ts. I think this is because locally, I don't have server.js since it is built during the image build phase, and since the volume is referencing that directory, it is not there in the container. Is there any way that I could build the container and have the transpiled js files from the build phase in that volume?

Upvotes: 1

Views: 888

Answers (2)

tzellman
tzellman

Reputation: 11

If I am understanding you correctly, you are trying to support two different scenarios:

  • use a pre-built/transpiled version of your code (default scenario)
  • if a volume is specified, use/hot-transpile code from a mounted volume (development scenario)

I don't have experience with your exact situation, but in situations where I wanted to support different runtime scenarios, I would put that logic in a bash script, and set that script as the entrypoint.

e.g.

# ...
COPY run-script run-script

# ...

ENTRYPOINT ["/bin/bash", "run-script"]

And your run-script could do something like check if a specific pre-determined directory/path exists, and perform a different action than the default of just running your bundled script.

Upvotes: 1

b0gusb
b0gusb

Reputation: 4731

An idea would be to copy your transpiled files into a different folder during the building of the image and link them to the /path/to/server.js/directory/in/container directory before you start node. The command in docker-compose would be something like:

command: bash -c "ln -s /path/to/built/files /path/to/server.js/directory/in/container; npm install ..."

Upvotes: 1

Related Questions