If you aren’t familiar with Visual Studio Code’s Dev Containers extension, how about give this short article a read first?
Now, let’s explore how to set up a TypeScript development environment within a Docker container.
Setting Up Your Project Structure
To begin, create a new directory for your project and set up the following structure:
root/
├── .devcontainer/
│ ├── devcontainer.json
│ └── docker-compose.yml
├── docker-compose.yml
├── Dockerfile
└── package.json
Step 1: Create devcontainer.json
This file configures your development container. Here’s a basic setup:
{
"name": "nodejs",
"dockerComposeFile": ["../docker-compose.yml", "docker-compose.yml"],
"service": "your-app-service",
"workspaceFolder": "/workspaces/your-workspace-folder",
"postStartCommand": "npm run dev --host 0.0.0.0"
}
Step 2: Configure docker-compose.yml
Files
You’ll need two docker-compose.yml
files: one inside .devcontainer/
and another in the root directory. Here’s how they should look:
.devcontainer/docker-compose.yml
version: "3"
services:
your-app-service:
image: node:latest
ports:
- 4321:4321
working_dir: /workspaces/your-workspace-folder
volumes:
- ./:/workspaces/your-workspace-folder
command: sleep infinity
docker-compose.yml
(root directory)
version: "3"
services:
your-app-service:
image: node:latest
ports:
- 4321:4321
working_dir: /workspaces/your-workspace-folder
command: npm run dev --host 0.0.0.0
volumes:
- ./:/workspaces/your-workspace-folder
Step 3: Create a Dockerfile
For now, keep this commented out. We’ll uncomment it once we have a package.json
file.
# Base stage for building the static files
# FROM node:lts AS base
# WORKDIR /workspaces/your-workspace-folder
# COPY package*.json ./
# RUN npm install
# COPY . .
# RUN npm run build
# # Runtime stage for serving the application
# FROM nginx:latest AS runtime
# COPY --from=base ./workspaces/your-workspace-folder/dist /usr/share/nginx/html
# EXPOSE 80
Step 4: Initialize Your Project
- Open the terminal in VS Code using `Ctrl + “.
- Run
npm init
to create apackage.json
file. - Install TypeScript as a dev dependency:
npm install typescript --save-dev
.
Step 5: Reopen in Container
Now that your project is set up, you can reopen it in a container:
- Open the Command Palette in VS Code (
F1
orCtrl+Shift+P
). - Select Dev Containers: Reopen in Container.
Your environment is now ready for TypeScript development within a container.
Setting up a TypeScript development environment in a container provides a clean, isolated space for coding. This setup ensures consistency across different environments and simplifies collaboration among developers. With these steps, you’re ready to start coding your TypeScript projects efficiently within a containerized environment.