This is how I use jquery in .js.erb when I use webpack and without asset pipeline.
(I assume that the Rails is created with something like $ rails new MyApp --webpack)
First of, I replace <%= javascript_include_tag 'application' %> with <%= javascript_pack_tag 'application' %> so we use javascript from /app/javascript/pack/application.js instead of /app/assets/javascripts/application.js
Add rails-ujs and jquery by running
$ yarn add rails-ujs jquery
modify /config/webpack/environment.js as following
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
// Add an additional plugin of your choosing : ProvidePlugin
environment.plugins.prepend(
'Provide',
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jquery: 'jquery/src/jquery'
})
)
module.exports = environment
The webpack configuration is reference from here
I make a test page like this...
in /app/views/pages/index.html.erb
<div class="index">
<h1 class="index--title">Index Title</h1>
<div class="index--jquery-test">
<%= link_to "jquery test", pages_index_path, remote: true %>
</div>
</div>
and in /app/views/pages/index.js.erb it has following code, that will run jquery when the link is clicked
$(function(){
console.log('run <%= "JQuery" %> from .js.erb')
})
In /app/javascript/pack/application.js import Rails and call Rails.start() to allow the date-remote in the link to work and to make unobtrusive javascript to call index.js.erb file.
I also try to see if jquery from within pack/application.js file is also work by calling console.log to show a title text that I got from jquery selector $('.index--title').text()
import Rails from 'rails-ujs'
Rails.start()
$(function() {
console.log($('.index--title').text())
})
When run Rails app at, let say, http://localhost:3000/pages/index you should see the 'Index Title' in console windows of the browser. And when click the link you should see 'run JQuery from .js.erb' in the console windows. I hope it works for you.