Rails and React: Fixing Module not found” errors for JSX files

Recently, whilst exploring how we can use React with Rails at Plymouth Software, we were coming up against an error trying to run the simple Hello World” tutorial for the React on Rails gem.

When compiling the assets through bin/webpack-dev-server or bin/rails assets:precompile, we were getting the following error message:

Module not found: Error: Can't resolve '../bundles/HelloWorld/components/HelloWorld' in '/path/to/code/react-on-rails-app/app/javascript/packs'

However, it turns out the message is a little misleading. I discovered this by accident by changing the import line:

# hello-world-bundle.js
- import HelloWorld from '../bundles/HelloWorld/components/HelloWorld'
+ import HelloWorld from '../bundles/HelloWorld/components/HelloWorld.jsx'

Trying to compile the assets again gave a different error:

HelloWorld.jsx: Support for the experimental syntax 'jsx' isn't currently enabled (8:5)

The error seems to be that the JSX (the HTML-in-Javascript template language used by React) could not be compiled.

But JSX should come as part of the React installation, so I tried re-running the webpacker react generator:

$ bin/rails webpacker:install:react

From the logs, I could see this added babel (amongst other things) to the package.json.

After restarting bin/webpack-dev-server and bin/rails s, the tutorial page worked as expected!

React on Rails Hello World Screenshot



Date
22 July 2020