Having trouble getting Bootstrap's Javascript to function properly in a Rails 6 webpacker configuration?

Recently initiated a brand new Rails 6.0.3 project and integrated jQuery and Bootstrap into it. Surprisingly, jQuery is functioning smoothly, and the Bootstrap CSS appears to be rendering correctly. However, every attempt to execute $.fn.tooltip.Constructor.VERSION in the browser's JavaScript console triggers an error message stating

Uncaught TypeError: Cannot read property 'tooltip' of undefined
. Furthermore, endeavors to include plugins like bootstrap-select, Bootstrap Tags Input, etc., are all unsuccessful. I have encountered similar challenges when attempting to incorporate awesome-fonts - where the CSS works but Javascript fails to function. Below are some configurations that may hold relevance:

// package.json
{
  "name": "myproject",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "5.2.1",
    "bootstrap": "^4.5.2",
    "channels": "^0.0.4",
    "jquery": "^3.5.1",
    "popper.js": "^1.16.1",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "axios": "^0.20.0",
    "cypress": "^5.1.0",
    "webpack-dev-server": "^3.11.0"
  }
}
// config/webpack/environment.js
const { environment } = require('@rails/webpacker')

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

module.exports = environment
// config/webpack/development.js
process.env.NODE_ENV = process.env.NODE_ENV || 'development'

const environment = require('./environment')

module.exports = environment.toWebpackConfig()
// app/javascript/packs/application.js
require("jquery")
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("bootstrap")
// app/views/layouts/application.html.erb
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

    <title>My Project</title>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

Answer №1

Managed to make it work by incorporating the following code snippet...

// config/webpack/custom.js
module.exports = {
  resolve: {
    alias: {
      jquery: 'jquery/src/jquery'
    }
  }
};

... and implementing these modifications:

// config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const customConfig = require('./custom')

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

environment.config.merge(customConfig)
module.exports = environment
// config/webpack/environment.js
require("jquery")
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("bootstrap")

import $ from "jquery"

document.addEventListener("turbolinks:load", () => {
  $('[data-toggle="tooltip"]').tooltip()
  $('[data-toggle="popover"]').popover()
})

Found a helpful post that assisted in reaching a solution: $(...).tooltip is not a function rails 6 webpack

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing React Typescript for Passing Props and Implementing them in Child Components

I'm currently working with React and TypeScript and attempting to pass data as props to a child component for use. However, I've encountered an error that I can't quite understand why it's happening or how to resolve it. Additionally, I ...

Validate the array with AJAX and display an error message

Need assistance validating arrays using FormRequest validation. The error message for the 'name' field can be accessed as data.responseJSON.error.name[0] and displayed to the user. error: function(data, xhr, errmsg, err){ console.log(" ...

Creating mathematical formulas in JavaScript

How can the equation be translated into JavaScript? This is the proposed programming solution, but there seems to be an issue. var MIR = parseFloat(($('#aprrate').val() / 100) / 12); var paymentAmount = (MIR * $('#amounttofinance').va ...

Deciphering occurrences in highcharts

When drawing a rectangle in highcharts using the selection event, I am able to retrieve the coordinates of the box by translating the axis values of the chart like this: chart.xAxis[0].translate((event.xAxis[0]||chart.xAxis[0]).min) Now, my query is how ...

Changing a background image url using jQuery by clicking a button

I'm struggling to find a way to use jQuery to add a background image URL to my CSS. Everything I've attempted so far has been unsuccessful. let button = document.querySelector('form button.btn') button.addEventListener('click&ap ...

Master the art of horizontal scrolling in React-Chartsjs-2

I recently created a bar chart using react.js and I need to find a way to enable horizontal scrolling on the x-axis as the number of values increases. The chart below displays daily search values inputted by users. With over 100 days worth of data already, ...

Steps for generating a div, link, and image that links to another image using Javascript

Hey there, I have a cool picture to share with you! <img src="cards.png" id="img"> <!--CARD PICTURE--> Check out what I want to do with it: <div class="container_img"> <img src="cards.png" id="img"> <!--CARD PICTURE--> ...

Using Vuejs to implement pagination on a weekly basis

I need some help with Vue pagination. I have a ticket object, and currently, it displays in a certain way. What I'm trying to achieve is to display the tickets weekly. For example, if this week is the 31st week of the year, then from today until Sunda ...

Query regarding timing in JavaScript

I recently started learning JavaScript and I am facing a challenge with running a check to determine if it is daylight. Currently, I am using Yahoo's weather API to retrieve information about sunrise and sunset times. The issue I have encountered is h ...

Using ReactJS and JavaScript to transform an array into a fresh array

I am working with an array that looks like this: var oldArray = [ {number: '12345', alphabet: 'abcde'}, {number: '54321', alphabet: 'abcde'}, {number: '67891', alphabet: 'abcde'}, ...

The application is experiencing extended loading times during production

After deploying my Angular 2 app on Heroku, I've noticed that it's taking a long time to load. Is there a way to bundle everything up instead of having all the scripts and stylesheets scattered across my index.html file? <html> <head> ...

Updating the DOM through Long Polling allows us to maintain existing attributes in jQuery Plugin

UPDATE: The functionality is all set; the pushes are working. The only issue I'm facing is that each push resets the #load_info div to empty. Is there a way to retain the original content inside the div, even though the content will be an updated vers ...

Is there a more effective way to structure my code than using multiple "IF/ELSE" statements?

Here is the current code snippet that I have: (category=="Ljud & Bild") ? byId("nav_sub_ljud_bild").style.display='block' : byId("nav_sub_ljud_bild").style.display='none'; (category=="Datorer") ? byId("nav_sub_datorer").style.disp ...

Utilizing Array Elements to Populate the Title Attribute in <TD> Tags

I am trying to display text on hover of a cell in my dynamically created HTML table, using the title attribute. However, instead of reading the contents of the array, it is displaying the array name as a string. Below is the code for generating the table ...

Troubleshooting the issue with a styled subcomponent in React using Styled Components

Recently, I've delved into React and have been experimenting with creating a Modal component using styled components. My goal is to achieve a similar effect to Framer Motion's motion.div, but utilizing styled components instead. Currently, I hav ...

Utilizing JavaScript as an alternative to PHP in this specific scenario

Hey everyone, I'm looking to pass data from PHP to JavaScript. Below is my PHP code that I need to adapt for use in JavaScript: $result = dbMySql::Exec('SELECT Latitude,Longitude FROM data'); while ($row = mysqli_fetch_assoc($result)) $ ...

Updating Parent Component Modal Properties Using Another Child Component - ReactJS

Greetings, I must mention that my knowledge of React is still in its early stages. Despite searching extensively on the internet for a solution to this particular issue, I have not been able to find one that fits perfectly, hence why I am reaching out here ...

What is the best way to anchor the components to a specific location on the screen in ASP.NET?

Currently I am working on creating a registration page in asp.net. I have been using panels to group the components such as labels, dropdown lists, and text boxes. However, when I run the page, I noticed that the positions of these components keep changing ...

Is there a way to transform integers into their matching strings within Vue markup?

I have a database table where I retrieve data. The "status" field is used to manage the information in this table. If the status is equal to 1, it indicates "Active." If the status is equal to 2, it signifies "Completed." If the status is equal to 0, it r ...

The NextJS homepage and API endpoint are combined on a single page

In my Next.js application, I have multiple pages and I want the component loaded at http://localhost:3000/someEndpoint to be exactly the same as the one loaded at http://localhost:3000/ I have already created an index.js file, but I am unsure how to creat ...