ruby-on-railswebpackwebpackerrails-ujs

Using Rails-UJS in JS modules (Rails 6 with webpacker)


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!


Solution

  • in my app/javascript/packs/application.js:

    import Rails from '@rails/ujs';
    Rails.start();
    

    and then in whatever module, controller, component I'm writing:

    import Rails from '@rails/ujs';