Rails .js.erb templates no longer work with Webpack

Viewed 1301

I've just switched my Rails app over to use WebPack to deal with assets etc. It's working well apart from I have some JS templates in my views directory (*.js.erb) . These require jQuery and as jQuery is pulled in as part of my WebPack bundles, it is not working in those templates.

Is there a way to allow those templates to work?

3 Answers

Well in order to make things work you need to include jquery using yarn which works with the latest version of rails.

In Rails 5.1 this is done with the new JavaScript packet manager Yarn which you have to install first

sudo apt-get install yarn

Then you can use it to install jQuery:

yarn add jquery

To actually load jquery you have to add this line

//= require rails-ujs
//= require jquery
//= require turbolinks
//= require_tree .

After installing jquery your js.erb file will start working Refer this article

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.

Related