What is Webpacker
webpacker is a gem which wraps
Webpacker wraps webpack in a Ruby gem and provides helpers to use the output from Webpacker in the Rails application.
When you create a new Rails 6 app, you will see following output in the console.
rails webpacker:install RAILS_ENV=development environment is not defined in config/webpacker.yml, falling back to production environment create config/webpacker.yml Copying webpack core config create config/webpack create config/webpack/development.js create config/webpack/environment.js create config/webpack/production.js create config/webpack/test.js
You will also find
webpacker gem in the
Gemfile by default. The
rails new command will also install tons of npm packages via
Old applications which are upgraded to Rails 6, do not get
webpackergem installed by default. You need to manually include it in Gemfile and then run
rails webpacker:install. We will cover how to use Webpacker in an existing Rails application in a latter blog post.
Let's go through the contents of this directory in a empty Rails 6 application.
It contains two directories,
channels directory is generated by Action Cable component of Rails. We can ignore it safely for now. The
packs directory is significant for us so let's see what it contains.
What is a pack?
application pack in the form of this
application.js file under
application pack generated by Rails contains code related to Rails components such as trubolinks, Active Storage and Action Cable.
This setting is configured by Webpacker for us in the file
# config/webpacker.yml 5: source_entry_path: packs
resolved_paths in the
config/webpacker.yml. The file is pretty self-explanatory in terms of the configuration options.
Live reloading using webpack-dev-server
Webpacker generates a file
bin/webpack-dev-server which can be used for live reloading in the development phase. We have to run the webpack-dev-server separately for this purpose and then we can see live reloading and hot module replacement in action.
In production, webpacker appends
webpacker:compile task to the
assets:precompile task. So if your build pipeline runs
assets:precompile task it will take care of compiling files to be compiled by webpack as well. As wepack package is part of
For that, Webpacker provides a helper method
That's all for today. We got an overview of how Webpacker enables us to use webpack in a Rails 6 application and we understood