Customize Stimulus Attributes, Avoid Conflicts

Stimulus is all about giving you front-end functionality with minimal JavaScript fuss and weight, but in certain cases, its data attributes can run into conflict with other libraries. I've recently made a pull request to add this to their docs, but for anyone else who's encountered this conflict, a little reconfiguration of the library's schema can keep your Stimulus implementation conflict-free.

Outside of a build system, Stimulus is initialized as documented in their handbook:

import { Application } from "https://unpkg.com/@hotwired/stimulus/dist/stimulus.js"
window.Stimulus = Application.start()

Stimulus uses HTML data attributes to target and add listeners to elements on the page. In Stimulus if you wanted a button to show a modal, you might write something like this:

<button data-action="modal#show">
Set up your profile
</button>

If you were to include Stimulus in a project that already had several JavaScript libraries, you may encounter what I encountered. The HTML attribute data-action was already being monitored by another library. Fortunately, after reading through their code I discovered there are parameters that can be passed to Application. The data attributes Stimulus looks for can be customized by passing a different "schema".

import { Application, defaultSchema } from "https://unpkg.com/@hotwired/stimulus/dist/stimulus.js"
const customSchema = {
...defaultSchema,
actionAttribute: 'data-stimulus-action'
}
window.Stimulus = Application.start(document.documentElement, customSchema)

This would allow you to create Stimulus event listeners using your custom attribute:

<button data-stimulus-action="modal#show">
Setup your profile
</button>

Stimulus is a great tool that gives you a lot of power on the front end for very little overhead— if you'd like to see a blog series from me to get a thorough introduction to the library, let us know!