How to use remote node_modules (inside container) on WebStorm?

Viewed 1322

I installed all npm dependencies inside to the container. So I don't want to install dependencies to my host machine. Everything is okay, it works. But there is a problem with Webstorm.

It says "Unresolved function" for npm dependencies. How to fix that problem? How can I say "Hey webstorm, node_modules directory is inside the container :)"

3 Answers

WebStorm expects node_modules to be located in the project folder.

You can try setting up NODE_PATH in Node.js run configuration template: Run | Edit Configurations..., expand Templates node, select Node.js configuration, specify NODE_PATH in Environment variables field

Please see comments in https://youtrack.jetbrains.com/issue/WEB-19476.

But I'm not sure it will work for modules installed in container...

Even though you expose the container's node_modules folder it's likely to not work as expected because npm dependencies are built according their host environment, which will not be the same as your local dev machine.

This statement applies even stronger if you want to run some CLI developments tools - which sometimes are compiled binary files.

TLDR;

Trick is to update the path inside docker container from /your-path to /opt/project.

Detail solution

The issue with webstorm is they don't allow you to define the path from where you can pick node_modules. But they have a default path from which they pick it. I was facing the same issue while I wanted to integrate remote debugging for a backend node service running inside docker.

You need to update your docker file. Suppose you were using Dockerfile was something like this

# pull official base image
FROM node:12.11-buster

# set working directory
WORKDIR /app

COPY ./package.json ./package-lock.json /app

RUN npm install

Now this won't be detecting the node_modules for remote debugging or any other integration you need in webstorm.

But if you update the dockerfile to something like this

# pull official base image
FROM node:12.11-buster

# set working directory
# This done particularly for enabling debugging in webstorm.
WORKDIR /opt/project

COPY ./package.json ./package-lock.json ./.npmrc /opt/project

RUN npm install

Then the webstorm is able to detect everything as expected.

Trick is to update the path from /your-path to /opt/project

And your docker-compose file should look something like this:

version: "3.7"
services:
  backend-service:
    build:
      dockerfile: ./Dockerfile.local
      context: ./
    command: nodemon app.js
    volumes:
      - ./:/opt/project
      - /opt/project/node_modules/
    ports:
      - 6060:6060
    

You can check more details around this in this blog

Related