Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are my js.erb views not working when using webpacker in Rails 6 with bootstrap?

Im trying to add som simple Ajax to my rails app. I am using Bootstrap with webpack. My webpack/environment.js file looks like this

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.append('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Popper: ['popper.js', 'default']
  })
)

module.exports = environment

My javascript/packs/application.js looks like this

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
import 'bootstrap'
import 'src/main'
import 'style/main'

I'm trying to add some Ajax for one of my models in create.js.erb

$("#question-<%= @exam_option.exam_question.id %>-options").append("<%= escape_javascript render 'exam_option', option: @exam_option %>");
$('#add_option_modal').modal('hide');

When I try and add one of my options, I get the console error

ReferenceError: Can't find variable: $

I've searched for a solution and have been unsuccessful.

What am I doing wrong? Thank you!

Edit:

When I added Bootstrap to my app, I followed this guide . When following the guide, I installed bootstrap, jquery and popper.js with yarn

yarn add bootstrap jquery popper.js

The jQuery that Bootstrap uses is working correctly (such as tooltips). as per @mechnicov's answer, I tried changing my environment.js to

const webpack = require('webpack')
environment.plugins.append('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery',
    Popper: ['popper.js', 'default']
  })
)

and I added require("jquery") above import 'bootstrap' in my application.js

when I made those changes, my code in create.js.erb works correctly, but it makes my Bootstrap not function correctly and throw errors such as TypeError: ... $('[data-toggle="tooltip"]').tooltip() undefined.

Edit 2

As per the accepted answer, I changed my application.js to :

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
window.jQuery = window.$ = require('jquery')
import 'bootstrap'
import 'src/main'
import 'style/main'

All seems to be working correctly, but I'm unsure why I need to add it this way? isn't Webpack supposed to do this from my environment.js file? If someone can explain this, please do.

like image 964
oobie11 Avatar asked Jan 01 '23 07:01

oobie11


1 Answers

Can you try below code :-

# javascript/packs/application.js

window.jQuery = window.$ = require('jquery')

OR

# javascript/packs/application.js

require("jquery")
window.jQuery = $;
window.$ = $;

I was also facing same problem but above code was worked for me at that time

Hope this will help you also. :)

like image 102
code_aks Avatar answered Jan 14 '23 14:01

code_aks