Using Rails-UJS in JS modules (Rails 6 with webpacker)
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';
First at all, using yarn add rails/ujs:
yarn add @rails/ujs
And add to config/webpack/environment.js
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default'],
toastr: 'toastr/toastr',
ApexCharts: ['apexcharts', 'default'],
underscore: ['underscore', 'm'],
Rails: ['@rails/ujs']
})
)
module.exports = environment
Config and load Rails js.
# pack/application.js
require("@rails/ujs").start()
global.Rails = Rails;
And Then: This is result ->
Just add it to your environment.js file, here is mine (with bootstrap and jquery):
const {environment} = require('@rails/webpacker')
const webpack = require('webpack')
module.exports = environment
environment.plugins.prepend(
'Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
"window.$": "jquery",
Popper: ['popper.js', 'default'],
Rails: ['@rails/ujs']
})
)
I am currently messing around on 6.0.0.rc2 but I think I got an answer for you.
So if you separate out the:
app/javascript/packs/application.js
require("@rails/ujs").start()
import "controllers"
To instead:
export const rails_ujs = require("@rails/ujs")
console.log(rails_ujs)
rails_ujs.start()
You can obviously remove that console.log was just trying to figure things out. Then in your stimulus controller you can simply do:
// Visit The Stimulus Handbook for more details
// https://stimulusjs.org/handbook/introduction
//
// This example controller works with specially annotated HTML like:
//
// <div data-controller="hello">
// <h1 data-target="hello.output"></h1>
// </div>
import { Controller } from "stimulus"
import { rails_ujs } from "packs/application.js"
export default class extends Controller {
static targets = [ "output" ]
connect() {
// this.outputTarget.textContent = 'Hello, Stimulus!'
console.log('hi')
console.log(rails_ujs)
}
}
Just using their little test controller here but I got it to console.log out and you can call rails_ujs.fire
so that should be what you want :)
Let me know if this works for you!