Webpacker in Rails6
Webpacker
- Webpacker is the JavaScript compiler which compiles the JavaScript code.
- Prior to Rails6, JS code were inside app/assets/javascripts
- In Rails6, no app/assets/javascripts and have new dir
app/javascript
to load all the js files which haschannels
&packs
and all Javascript components like Turbolinks, ActiveStorage, Rails-UJS, ActionCable support Webpacker. - Other dir
channels
generated by Rails ActionCable component - Another dir
packs
which has app/packs/javascripts
app/javascript/packs/application.js
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
- any js files inside packs/ will autocompiled by Webpack
About Pack
- Webpack uses
webpacker gem
which wraps webpack and used to compile the javascript code which are on the packs directory. This gem creates the application pack as application.js inside app/javascript/packs which is similar to assets pipeline (app/assets/javascripts/application.js) andapplication
pack is the entry point for all the JavaScript code that contains Action Cable, Active Storage, Turbolinks Rails components. gem webpacker
is automatically placed inside the Gemfile of Rails6 application, andyarn
is used to install npm packages when creating new Rails 6 application.
Gem also generates settings:
config/webpacker.yml
- As like assets pipeline, JavaScript code using Webpacker and webpack automatically compiles in development mode when running rails server.
- Gem also generates the file
bin/webpack-dev-server
which is used to live reloading the development phase. Inorder to see the live reloading in development mode we need to run the webpack-dev-server with command./bin/webpack-dev-server
separately. - However, in production mode,
rake assets:precompile
also override therake webpacker:compile
which will compile the assets pipleline and compile the files to be compiled by webpack which updates the package.json.
Way to use the JavaScript code in the app
we can use the helper method javascript_pack_tag
to include the webpacker packs file which is similar to asset pipeline javascript_link_tag
and works on both development and production mode.
# app/views/layouts/application.html.erb
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
- Prior to Rails 6 application do not install
gem webpacker
by default, include it in Gemfile, and run the commandrake webpacker:install
This post is licensed under
CC BY 4.0
by the author.