Skip to main content

Command Palette

Search for a command to run...

Docker build fix for TypeScript

Updated
1 min read
D

I like to automate things and enjoying tinkering my system.

Issue

When building a docker image generally, we skip installing dev dependencies for production

# Skips installing dev dependencies
RUN npm ci --only=production

But when working with TypeScript you need tsc which is a dev dependecy to compile the TypeScript to JavaScript into ./dist folder

Solution

Changed the Dockerfile to install all dependencies first, build, then remove dev dependecies:

# Install ALL dependecies (including dev dependecies for build)
RUN npm ci

# Copy source code
COPY tsconfig.json ./
COPY src ./src

# Build TypeScript
RUN npm run build

# Remove dev dependecies and source files after build
RUN npm prune --production && \
    rm -rf src tsconfig.json

Key Changes

  1. Changed npm ci —only=production to npm ci (installs all deps)

  2. Build happens with TypeScript available

  3. After build, npm prune —production removes dev dependencies

  4. Final image is still lean, only containing production deps and built code

Why This Works

  1. Install phase: Gets all dependencies including TypeScript

  2. Build phase: TypeScript compiler is available

  3. Cleanup phase: Removes unnecessary dev dependencies

  4. Result: Small production image with only what's needed to run

Try Again

Run the docker build cmd again this time, it will complete successfully! ✅