Last updated Tue, Aug 9, 2022

Devcontainers for frontend development

Frontend

Introduction

There is a VSCode extension by Microsoft called “Remote - Containers” which allows development inside of Docker containers, with configuration managed as code (within a devcontainer.json file).

This has some nice features, namely:

  • The version of node and other global tools (like PNPM) are managed by the Dockerfile in the repo, developers don’t need to manually manage it on their host machine.
  • The node_modules is stored within a Docker volume, not on the host operating system. This can improve the speed of installs/builds particularly if the host operating system is Windows (cause of AV scanning, slow file system, etc.)

Experiment with a Next.js App

  1. Create a new Next.js app with typescript
  2. Install the Remote Containers VSCode extension
  3. Create the config files:
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.241.1/containers/docker-existing-dockerfile
{
  "name": "My Next.js App",

  "context": "..",

  "customizations": {
    "vscode": {
      "settings": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
      },
      "extensions": ["mutantdino.resourcemonitor", "esbenp.prettier-vscode"]
    }
  },

  "dockerFile": "../Dockerfile",
  "mounts": [
    "source=my-next-app-node_modules,target=${containerWorkspaceFolder}/node_modules,type=volume"
  ],

  // Use 'forwardPorts' to make a list of ports inside the container available locally.
  "forwardPorts": [3000],

  "postCreateCommand": "pnpm install"
}

.devcontainer/devcontainer.json

FROM node:latest

RUN npm i -g pnpm

Dockerfile

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  webpack: (config) => {
    // Workaround for Next not detecting changes within a container
    config.watchOptions = {
      aggregateTimeout: 200,
      poll: 1000,
    };

    return config;
  },
};

module.exports = nextConfig;

next.config.js

  1. Open the folder in VSCode, check bottom lefthand corner to check if the devcontainer starts up

Resources