Bootstrap JS functions not loading in Rails 6/Webpacker

ぐ巨炮叔叔 提交于 2019-12-25 00:28:14

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/58195417/bootstrap-js-functions-not-loading-in-rails-6-webpacker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!