Hanami 1.3 > Hanami 2.2 : tips & notes about my journey

Use case #5: import js libraries (like HTMX or Alpine)

In my Hanami 1.3 app I imported a few js libs with a plain old <script> tag referencing the js files placed manually in the assets.

With a great assets pipeline in place in Hanami 2, I wanted to import js libraries in a clean way. Nothing fancy, and it’s already covered in the main doc, but I thought it was worth explaining the few steps needed.

First you need to add the libraries yout want as npm dependencies in packages.json, for example:

{
  "name": "myapp",
  "private": true,
  "type": "module",
  "dependencies": {
    "hanami-assets": "^2.2.1",
    "htmx.org": "^2.0.6",
    "alpinejs": "^3.14.9"
  },
  "devDependencies": {
    "esbuild": "^0.25.4",
  }
}

You can then download the packages with npm install

The libraries are now ready to be included in your main js file, for example for a specific slice slices/backend/assets/js/app.js:

import "htmx.org/dist/htmx.js"

import Alpine from 'alpinejs'
window.Alpine = Alpine
Alpine.start()

This main js file itself has to be included in your layout slices/backend/templates/layouts/app.html.erb

<%= javascript_tag "app" %>

The js libraries are now loaded with each page!

Note: I also needed to tweak the CSP directives for the slice in order to make the libraries work, I’ll treat that in my next use case