A couple of my projects used react-rails to render React components on the server-side using the legacy Sprockets system. This worked well, but I wanted to migrate to Webpacker to easily upgrade to the newest versions of React and React Bootstrap (previously I imported this using the reactbootstrap-rails, but this stopped being maintained with the launch of Webpacker.) However, migrating React components to support Webpack required changes to every single file adding ES6-style imports, file moves/renames, and scoping changes. This would have been too large to do all at once. What if there was a way to slowly migrate the JS code from Sprockets to Webpack, making components in either side available to the other side?
Here outlines a guide on how to migrate an existing Sprockets-based Rails application to start using Webpacker. After this, we’ll have 2 different
Enable Webpacker and add React
Note: The Webpacker gem includes more detailed instructions.
Add Webpacker gem to Gemfile:
This must be loaded in development, production, and during asset compilation.
rails generate react:install
Load React through Webpack
Now that React has been installed and is available in the node_modules folder, we need to load it in the Webpack JS context and make it available on the client-side to Sprockets. We can attach it to window.React, etc. to share it with other components.
Expose Webpack to Asset Pipeline