Ken Muse

Dev Containers and node_modules


Dealing with node_modules can create quite the challenge, especially in a larger Node.js project. As the number of dependencies grows, so does the size of the node_modules. Of course, trying to clean up the folder creates its own issues. Operating systems are always slow when it comes to removing large numbers of small files. Thankfully, there’s a way you can avoid this hassle using dev containers.

A minor adjustment to your devcontainer.json file is all it takes to avoid this problem:

1"mounts": ["source=node_modules,target=${containerWorkspaceFolder}/node_modules,type=volume"],

This works by mounting a Docker volume in place of the workspace’s node_modules folder. When the container is started the next time, a new volume will be created. As you install dependencies, the files are saved to the volume. This allows them to be persistent and available each time you restart the container. When you’re done working with the container, simple remove the volume. Because it’s acting as a virtual disk, the files do not have to be individually deleted. They are removed with the volume. Restarting the container will re-create the volume, allowing the cycle to continue. Outside of the dev container, only a node_modules folder will exist. It’s automatically created (similar to the volume) as part of the mounting process.

Easy, right?

Beyond this use, mounts can allow you to use in-memory file systems, or share files into your dev container from the local computer. But that’s a topic for next week. Until then, Happy DevOp’ing!