How to Install Alpine JS 3 with Rails 6.1 via Webpacker

Viewed 754

Ever since AlpineJS upgraded to Alpine 3, I haven't been able to get it working with Rails 6 and webpacker, I've only been able to get it working when linking to the CDN version of Alpine.

In the past with AlpineJS 2 I've just had to run yarn add alpinejs then put require('alpinejs') in javascript/packs/application.js.

From everything I've read, it seems that when using Turbo on Rails 6.1 I need to do this:

// Alpine JS
import 'alpine-turbo-drive-adapter'
require('alpinejs')

(After installing the packages, obviously). I'm loading my javascript in my html header with <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>.

But, that still doesn't work. Does th AlpineJS NPM package just not work with webpacker and Rails?

How do I get this working instead of loading from the Alpine JS CDN?


UPDATE:

I made sure to run yarn add alpinejs and yarn add alpine-turbo-drive-adapter. I've also updated my packs/application.js file to make sure it is using Turbo and not Turbolinks. It looks like this now:

import Rails from "@rails/ujs"
import "@hotwired/turbo"
import * as ActiveStorage from "@rails/activestorage"
import "channels"

Rails.start()
ActiveStorage.start()

import "controllers"

// Custom JS files
import 'alpine-turbo-drive-adapter'
import Alpine from "alpinejs"
window.Alpine = Alpine
Alpine.start()

// require("./components/direct_uploads")
require("stylesheets/application.scss")

After those two updates, I'm now getting this console error:

TypeError: func(func, completeScope).catch is not a function. (In 'func(func, completeScope).catch(function (error2) {
        return handleError(error2, el, expression);
      })', 'func(func, completeScope).catch' is undefined)
3 Answers

AlpineJS 3 requires webpack 5 and therefore the (currently) unreleased webpacker 6, so you can try using the release candidate of webpacker 6 or use the CDN version of AlpineJS 3 for the time being.

As an alternate, there are some new gems that can be used with Rails such as https://github.com/rails/jsbundling-rails and https://github.com/rails/importmap-rails. If you want to stick with webpack, then the jsbundling-rails gem is probably a better option than webpacker now.

It looks like a incompatible version issue...

In package.json set specific version to alpine and alpine-turbo-drive-adapter:

"alpine-turbo-drive-adapter": "1.1.0",
"alpinejs": "3.2.3",

Don't forgot remove your (yarn.lock or package.json.lock) and run (yarn install or npm install).

In application.js import:

import Alpine from 'alpinejs'
window.Alpine = Alpine
$(() => {
  Alpine.start();
});

I hope it works for you!

Related