typescriptdockernestjsnpm-build

nestjs build error for dev-dependency module ts-loader


I'm getting following Module Error for ts-loader while docker build

ERROR [6/6] RUN nest build                                                                                                                                3.9s
------
 > [6/6] RUN nest build:
#10 3.863 ERROR in main
#10 3.863 Module not found: Error: Can't resolve 'ts-loader' in '/user/src/app'
#10 3.863 resolve 'ts-loader' in '/user/src/app'
#10 3.863   Parsed request is a module
#10 3.863   using description file: /user/src/app/package.json (relative path: .)
#10 3.863     resolve as module
#10 3.863       looking for modules in /user/src/app/node_modules
#10 3.863         single file module
#10 3.863           using description file: /user/src/app/package.json (relative path: ./node_modules/ts-loader)
#10 3.863             no extension
#10 3.863               /user/src/app/node_modules/ts-loader doesn't exist
#10 3.863             .js
#10 3.863               /user/src/app/node_modules/ts-loader.js doesn't exist
#10 3.863         /user/src/app/node_modules/ts-loader doesn't exist
#10 3.863       /user/src/node_modules doesn't exist or is not a directory
#10 3.863       /user/node_modules doesn't exist or is not a directory
#10 3.863       /node_modules doesn't exist or is not a directory
#10 3.863
#10 3.863 webpack 5.73.0 compiled with 1 error in 2169 ms

Following is the Dockerfile I'm using

FROM node:18-alpine

ENV TEST_ENV=docker_baap
ENV PORT=3500
WORKDIR /user/src/app
 
COPY . .
RUN npm i -g @nestjs/cli@9.0.0
RUN npm ci --omit=dev
 
RUN nest build
 
USER node
 
CMD ["npm", "run", "start:prod"]

the error is caused due to npm ci --omit=dev but how can it be resolved for production environment?


Solution

  • You need dev dependencies to build the application, but not to run it.

    You can do a multistage docker build.

    In the first stage you install all dependencies and build the application.

    In the second stage, you only install production dependencies and copy built application(/dist) from first stage.