Alpine.js custom directive alias

How to setup a custom alpine.js directive alias like @click


Alpine.js exposes a method/function from the Alpine instance that allows us to register directiveTransformers for alpine to use when traversing the dom and figuring out if it should parse it as a directive or not.

Alpine.mapAttributes();

But how to use it?

Alpine’s core contains these functions for helping with registering a “transformer” (I use typescript so you get the types here aswell):

type Attribute = {
  name: string;
  value: string | (() => unknown);
};

let startingWith =
  (subject: string, replacement: string) =>
  ({ name, value }: Attribute) => {
    if (name.startsWith(subject)) {
      name = name.replace(subject, replacement);
    }
    return { name, value };
  };

let into = <T>(x: T) => x;

Then you could just do it like this:

Alpine.mapAttributes(
  startingWith("thealiasyouwant", into(Alpine.prefixed("the-directive")))
);

or if you don’t want to make helper functions for it:

Alpine.mapAttributes(({ name, value }) => {
  if (name.startsWith("thealiasyouwant")) {
    name = name.replace("thealiasyouwant", Alpine.prefixed("the-directive"));
  }

  return { name, value };
});

Alpine.prefixed will return the passed in string prefixed with your alpine instance’s prefix.

for example, say we want to listen to events with event: instead of x-on, then we would do it like this:

Alpine.mapAttributes(startingWith("event:", into(Alpine.prefixed("on:"))));

Then when alpine encounters event:some-event when traversing, it will transform it to x-on:some-event before checking if it is an alpine directive!