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!
Taking into consideration all the major shifts in modern Javascript development, Rails 7 has decided to replace Webpacker with importmapped Hotwire as default the JavaScript setup. This means that a default Rails skeleton will not have to require the full JavaScript toolchain with Webpack by default.
you only need require rails_ujs , otherwise if you are doing any type of submission from client (for example), an alert will process twice.
With webpack, you can manage JavaScript, CSS, and static assets like images or fonts. Webpack will allow you to write your code, reference other code in your application, transform your code, and combine your code into easily downloadable packs.
Rails UJS (Unobtrusive JavaScript) is the JavaScript library that helps Rails do its magic when we use options like remote: true for many of the html helpers. In this article I'll try to explain the main concept of how this works to make it transparent for the user.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With