I believe I’ve integrated Stimulus with my Rails/TL app as I can print simple logs from connect methods. However, when trying to reference targets I get a syntax error.
Just an FYI, that same error message shows in the Glitch examples, but they do seem to work. I haven’t yet tried moving the examples outside of Glitch though.
This looks to be caused by a missing transformation. There is a closed issue on the Github when using babel. I’m not sure what the solution is when using the asset pipeline, but hopefully that helps.
Until the static class fields proposal is standardized, you’ll need the transform-class-properties plugin for Babel. See the Using Babel section of the installation guide for more details and an example configuration.
You can also use TypeScript, which has support for static class properties built-in.
If I try something like this using TypeScript, I get something like a “property hrefTarget does not exist on type default” error in compile? How do you get Typescript to learn the dynamic target methods?
Just for the heck of it, if you are using TypeScript with strictNullChecks: true then the declaration has to be something like this:
import { Controller } from "stimulus"
export default class extends Controller {
nameTarget: Element | undefined
static targets = [ "name" ]
actionThing() {
this.nameTarget!.classList
}
}
In other words, even though the nameTarget method will raise an exception rather than return undefined, TypeScript doesn’t know that, and forces you to both allow for the possibility when declaring the target and bypass it with !. when using the target.
I think, but I’m not sure, that this could be cleaned up by explicitly specifying the return values of the dynamically generated properties in target_properties.ts, rather then letting TypeScript infer them.