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';
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']
})
)
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 ->