Why we write this guide
There are several reasons:
- The official guide provides very little info.
- We underestimated the effort to do this. This long post explains our similar experience.
- Yet, that long post doesn't give a brief step-by-step guide. So, we decide to fill the gap.
1. Add Webpacker to Gemfile
We recommend you to leave the sprockets gem in your Gemfile if it's still needed. Or, if you plan to move gradually. Don't worry because both of them won't interfere with each other.
At the last of this step, make sure you've run the bundle install command.
2. Configure the webpacker gem
There are many configurations on the webpacker documentation. Here, we'll focus on these three, to make you easier to start:
Let's start with custom_loader.js. In this file, we use json-loader and yaml-loader as an example.
We believe other Rails projects will need this rails-erb-loader too.
The last one is production.js. Well, you can only use production.js or development.js here. Here's why: basically, webpacker is a wrapper for Webpack. Webpack only accepts production or development. Don't expect NODE_ENV to follow rules that RAILS_ENV follows.
Here, the production.js will inherit the configurations defined on config/webpack/environment.js
There, we call the rails-ujs and Rails Activestorage.
Why rails-ujs? In our case, and it must be the case for other Rails apps too, Rails will have a CSRF problem without rails-ujs.
It's also important to make sure you include this line in application.js
This kind of error is easily overlooked because the tests won't detect this by default. If we're looking at the Rails codes on github, Rails disable CSRF token by default on test mode.
If your Rails project is still using jquery-ujs, you'll need to migrate to rails-ujs first. We'll cover this in another article "How to migrate from jquery-ujs to rails-ujs".
Here, you and your team need to decide:
It will vary among projects. For simple projects, it's possible to migrate all of them.
7. Set up the global variables if your app needs it
Unlike sprockets, we need to define the global variables on Webpacker.
There is a variable called example1 in example1.js.
Then, you need to call it on example2.js. It isn't straightforward. You'll need something like these:
8. Call those migrated files in application.js
Use the "require" syntax for this.
9. Call this new application.js on the application.html.erb
10. Make sure everything works correctly
In our projects, we have integration tests with a capybara. Besides them, we also do thorough manual testing after the migration to Webpacker.
- Migration from Sprocket to Webpacker requires quite an effort. Don't underestimate it.
- Fortunately, we can run both sprocket and webpacker gem in a Rails app, without causing any problem.