How to share typescript code between two Dockerfiles
I had this same problem, but for sharing files between two typescript projects. Some of the other answers didn't work for me because I needed to preserve the relative import paths between the shared code. I solved it by organizing my code like this:
api/ Dockerfile src/ models/ index.tsfrontend/ Dockerfile src/ models/ index.tsshared/ model1.ts model2.ts index.ts.dockerignore
Note: After extracting the shared code into that top folder, I avoided needing to update the import paths because I updated api/models/index.ts
and frontend/models/index.ts
to export from shared: (eg export * from '../../../shared
)
Since the build context is now one directory higher, I had to make a few additional changes:
Update the build command to use the new context:
docker build -f Dockerfile ..
(two dots instead of one)Use a single
.dockerignore
at the top level to exclude allnode_modules
. (eg**/node_modules/**
)Prefix the
Dockerfile
COPY
commands withapi/
orfrontend/
Copy
shared
(in addition toapi/src
orfrontend/src
)WORKDIR /usr/src/appCOPY api/package*.json ./ <---- Prefix with api/RUN npm ciCOPY api/src api/ts*.json ./ <---- Prefix with api/COPY shared usr/src/shared <---- ADDEDRUN npm run build
This was the easiest way I could send everything to docker, while preserving the relative import paths in both projects. The tricky (annoying) part was all the changes/consequences caused by the build context being up one directory.