Blog

Thoughts from my daily grind

Install Webpacker in Older Rails

Posted by Ziyan Junaideen |Published: 28 March 2021 |Category: Code
Default Upload |

Depending on who you ask, the preferred means of installing client side packages to a Rails project differ from one developer to the other. I my self have used /vendors folder, gems, bower and rails-assets project. This all changed when Webpacker took stage. It was the most welcoming change I saw in a very long time.

I was under the impression Webpacker was Rails 5.1+ which was the case when it was released if I recall correctly. How ever with the Rails Assets project search not working I gave it a try with a legacy Rails 4.2+ project and it worked.

Installation

The installation is pretty much what the Webpacker project readme files suggests.

Add the Webpacker gem to the Gemfile and run bundle install. Webpacker v6 is in pre-release and v5.2.1 is the last stable release. How ever if we want to use them, we will have to update Rails, which we should have long time ago. After all support for Rails 4 has reached end-of-life.

In your project root, run the following command to add a compatible version of Webpacker to the project.

bundle add webpacker

Once done you don't have to run bundle. If for some reason that doesn't work for you, you add it manually to your project and bundle install it.

gem 'webpacker'

Prerequisites

If you are rocking Ruby on Rails, you would already have Node JS installed. If its not up to date, it will be a good time to do so. Then you need to add yarn.

npm install --global yarn

Configuring Project

Fortunately Webpacker is not a project that needs that much configuration. There is the generator that generates the necessary project files and structure. Once triggered you are good to go.

rake webpacker:install

This will install app/javascripts/packs/application.js. We don't need to use this. You can import it in your app/assets/javascripts/application.js file. For me it is application.coffee.

#= require jquery
#= require jquery_ujs
#= require bootstrap
#= require clipboard/dist/clipboard
#= require_self

Binstub Error

If this step fails with an error suggesting there are missing binstubs, you can generate them using rake rails:update:bin

➜  /vagrant git:(test/webpacker) ✗ rake webpacker:install
rake aborted!
Errno::ENOENT: No such file or directory - ./bin/rails

then...

rake rails:update:bin

Usage

Usage is as always easy as yarn add clipboard etc. I am not sure if its npm or yarn, but I remember a command like yarn install clipboard --save to add it to the package.json file. That is not supported in newer versions of yarn.

Tags
About the Author

Ziyan Junaideen -

Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.

Comments