Creating and configuring your Ruby on Rails project
$ brew install yarn $ brew install yarn --without-node
The next step is to create a Ruby on Rails project with –webpack param. (Please note that this only works with Rails 5+.)
$ rails new webapp --webpack
In your Gemfile, add the Webpacker gem and then run bundle to download Webpacker into your project..
gem 'webpacker', '~> 3.5' $ bundle
Now, running the following installs Webpacker in your application.
$ bundle exec rails webpacker:install
That’s it. The Ruby on Rails project is now completely functional with Webpacker.
Understanding the Webpacker structure
We can verify that inside the directory, app/assets has a new folder called config, and inside that we have a manifest.js file that links the folders stored in the app/assets directory.
In the webpacker.yml file, we have the extension key that set up the extension files linked, and here we can define the CSS preprocessors used (SASS/SCSS). And we also have the configuration of the dev-server.
Lastly, we have a webpack folder inside the config directory. There is one file for each environment that could be edited to include the code used when Webpack starts.
Including Webpack files
Let’s create a new controller (called Home) and generate the view (called index) for our project.
$ rails generate controller home index
Next, add some styles:
We also need to include application.css in our layout template.# app/views/layout/application.html.erb <%= stylesheet_pack_tag 'application.css' %>
That's it! Now, let's see how to run Webpack and view the result.
Or we can start the Rails server as usual:$ rails s
And access our page in the browser with this address: http://localhost:3000/home/index
The result is shown in the image below.
The setup of Webpacker 3.0 is not as easy (as compared to older versions), but it is much more comprehensive, which will be apparent to anyone who is already familiar with npm package configuration. It provides better performance, agility in development, and allows customization of the dev-server — with the promise of more changes with Rails 6.