i just switched to Rails 6 (6.0.0.rc1) which uses the Webpacker gem by default for Javascript assets together with Rails-UJS. I want to use Rails UJS in some of my modules in order to submit forms from a function with:
const form = document.querySelector("form")
Rails.fire(form, "submit")
In former Rails versions with Webpacker installed, the Rails
reference seemed to be "globally" available in my modules, but now i get this when calling Rails.fire
…
ReferenceError: Rails is not defined
How can i make Rails
from @rails/ujs
available to a specific or to all of my modules?
Below my setup…
app/javascript/controllers/form_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
// ...
submit() {
const form = this.element
Rails.fire(form, "submit")
}
// ...
}
app/javascript/controllers.js
// Load all the controllers within this directory and all subdirectories.
// Controller files must be named *_controller.js.
import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"
const application = Application.start()
const context = require.context("controllers", true, /_controller\.js$/)
application.load(definitionsFromContext(context))
app/javascript/packs/application.js
require("@rails/ujs").start()
import "controllers"
Thanks!
form_controller.js
form a npm package in order to reuse it across several rails applications. Is there any downside in doingimport Rails from "@rails/ujs"
several times across different controllers? If not, i'd mark this one as accepted answer. – Dixon