Mixing Laravel and Rails

Published 3 months ago

This information is pretty much just a regurgitation of a Japanese post I found here. I didn't find anything on the topic of using Laravel Mix with Rails in English, so I thought I'd write this technique up myself. I love Laravel and its asset system Mix. The combo of Rails and Webpacker kind of sucks. I used to think Rails was amazing, but then I found Laravel and I saw how forward thinking the Laravel community is in regards to the frontend. They embrace the frontend and its trends, while the Rails community seems to fight against it whenever it can. So let's find a way to use the frontend and all its wonderful abilities while still having access to Ruby on the backend.

Inside laravel_mix_helper.rb, drop this inside:

module LaravelMixHelper
  class LaravelMixError < StandardError; end
  MANIFEST_FILE = 'public/mix-manifest.json'
  def mix(path)
    unless File.exists?(MANIFEST_FILE)
      raise LaravelMixError.new('The Mix manifest does not exist. Run `npm run dev`.')
    manifest = JSON.parse(File.read(MANIFEST_FILE))

Inside webpack.mix.js, include this:

let mix = require('laravel-mix');
  .js('resources/js/app.js', 'public/js')
  .postCss('resources/css/app.css', 'public/css')
// Cache-busting
if (mix.inProduction()) {

Then, in your app/views/application.html.erb, reference your new asset files like this.

<link rel="stylesheet" href="<%= mix('/css/app.css') %>">
<script src="<%= mix('/js/app.js') %>"></script>

Now you can run npm run watch to get your dev server going, and run npm run production when you're ready to push. Relatively easy to set up, and way better than Webpacker.