Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap JS functions not loading in Rails 6/Webpacker

Climbing the learning curve with Webpacker and Rails 6.

I've installed Boostrap 4 using Yarn and Webpacker. When I try play with Bootstrap components in a browser's JS console then I get: TypeError: $.fn.button is undefined.

If I remove the Yarn installation add a Bootstrap CDN link in the head of the HTML (the old way) everything works fine. When I remove the CDN links and revert to using Webpacker I get back to the error above.

Here is my Webpacker setup:

// package.json
{
  "name": "depot",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0-alpha",
    "@rails/activestorage": "^6.0.0-alpha",
    "@rails/ujs": "^6.0.0-alpha",
    "@rails/webpacker": "^4.0.7",
    "bootstrap": "4.2.1",
    "jquery": "^3.4.1",
    "popper.js": "^1.15.0",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.8.0"
  }
}
// enviornment.js
const { environment } = require("@rails/webpacker");

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

module.exports = environment;
// application.js

require("@rails/ujs").start();
require("turbolinks").start();
require("@rails/activestorage").start();
require("channels");
require("jquery");
require("bootstrap");

import "./src/application.scss";
# layouts/application.html.haml
!!!
%html
  %head
    %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}
    %title Depot
    = csrf_meta_tags
    = csp_meta_tag
    = stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
    = javascript_pack_tag 'application', 'data-turbolinks-track': 'reload'

Is there something I should be doing to export the Bootstrap functions to the global namespace?

like image 932
Gazza Avatar asked Oct 02 '19 04:10

Gazza


1 Answers

Found a forum where this was discussed: https://gorails.com/forum/how-to-use-bootstrap-with-webpack-rails-discussion

They mentioned it could be caused by having jQuery loading multiple times, with the latest declaration preventing Bootstrap's JS from loading. I couldn't find any evidence of this in my project.

For me the fix ended up being a few lines added to the webpack entry point that exposed jQuery to the browser:

# packs/application.js

import JQuery from 'jquery';
window.$ = window.JQuery = JQuery;
like image 85
Gazza Avatar answered Oct 22 '22 14:10

Gazza