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/javascriptto load all the js files which haschannels&packsand all Javascript components like Turbolinks, ActiveStorage, Rails-UJS, ActionCable support Webpacker. - Other dir
channelsgenerated by Rails ActionCable component - Another dir
packswhich 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 gemwhich 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) andapplicationpack is the entry point for all the JavaScript code that contains Action Cable, Active Storage, Turbolinks Rails components. gem webpackeris automatically placed inside the Gemfile of Rails6 application, andyarnis 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-serverwhich 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-serverseparately. - However, in production mode,
rake assets:precompilealso override therake webpacker:compilewhich 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 webpackerby default, include it in Gemfile, and run the commandrake webpacker:install
This post is licensed under
CC BY 4.0
by the author.