Search code examples
ruby-on-railswebpackreact-rails

React-Rails 6 - Unable to import node_modules package


I'm trying to use an npm package in my react-rails project but can't seem to successfully import it. I first ran the following:

yarn add @mapbox/mapbox-gl-draw

Then, I tried both of the following import styles:

import * as MapboxDraw from '@mapbox/mapbox-gl-draw';
const MapboxDraw = require('@mapbox/mapbox/gl-draw');

However both of these generated the exact same error:

 Module not found: Error: Can't resolve '@mapbox/mapbox-gl-draw' in '/opt/app/myrailsapp/app/javascript/src/scenes/myscene.jsx'

How can I properly use a standard npm package inside a react-rails project? I've also tried moving those above statements to my application.js pack to no avail


Solution

  • The problem ended up being due to using containers and only running yarn install locally on one of my containers. I have the following docker-compose.yaml:

    services:
      myapp:
        # ...
        build:
          context: myapp/.
          dockerfile: Dockerfile.development
    
      webpacker:
        # ...
        build:
          context: myapp/.
          dockerfile: Dockerfile.development
    

    When I tried installing the package, I only ran

    docker-compose exec myapp yarn install @mapbox/mapbox-gl-draw
    

    This installed fine, but only for that container. I also needed to run that on the webpacker container. It appeared as if the package was installed correctly when in reality the webpacker container did not contain the package.

    Since installing node modules is apart of my Dockerfile, the fix was to run docker-compose build