WebPack on Rails! – the easiest way to use the new Javascript syntax on your rails apps with the newest frameworks

I had some rails projects that needed a better UI or a different feature in the UI, and there was the perfect javascript library, the problem was that it needed “require.js” and it is not really easy to integrate require.js in asset pipeline.

The good news is that there is a webpack gem that will do all the work for us…

And after rails 5.1 you can just

rails new myapp --webpacker

but lets assume you have an existing app, the changes are a little bigger, but we can use both the old asset pipeline and the new webpacker.

Lets start adding the webpacker gem to the Gemfile

gem 'webpacker'

Then just run:

bundle install
rails webpacker:install

After this, you have a new file, calledĀ app/javascript/packs/application.js where you can use

var mylib = require('myjslibrary');

You’ll be able to require there any javacript you create in the app/javascript directory (instead of app/assets/javascript), and any library you add to the application using the yarn executable.

To add a library requirement use:

yarn add myjslibraryname

And do no forget to run in your deploy server:

yarn install

After commiting the yarn.lock file of course, that file will make sure you have the same library versions in all the machines your project is running.

And last, but not least, do not forget to add the the script tag to call that file to your layout using the code:

<%= javascript_pack_tag 'application' %>

And of course you do not need to remove the old javascript_tag file, allowing you to keep using both asset pipeline version and the new webpacker version.

In this new file, you can use the all new requirejs syntax, and of course that is not all, you can add css to the app/javascript directory and insert in the layout with the <%= stylesheet_pack_tag ‘application’ %>, and the gem has shortcuts to use all the new and fancy javascript APIs, for example:

rails webpacker:install:angular          # Install everything needed for Angular
rails webpacker:install:coffee           # Install everything needed for Coffee
rails webpacker:install:elm              # Install everything needed for Elm
rails webpacker:install:erb              # Install everything needed for Erb
rails webpacker:install:react            # Install everything needed for React
rails webpacker:install:stimulus         # Install everything needed for Stimulus
rails webpacker:install:typescript       # Install everything needed for Typescript
rails webpacker:install:vue              # Install everything needed for Vue

Any of these shortcuts will install the required files to use the specified library in your existing rails app.

This is it for now, it is a good start I think.

Please comment any questions you have and I’ll answer it the fastest I can!