如果Bootstrap加载了Webpack(Rails),则modal()之类的方法将不起作用 [英] Methods like modal() not working if Bootstrap loaded with Webpack (Rails)

查看:48
本文介绍了如果Bootstrap加载了Webpack(Rails),则modal()之类的方法将不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Rails 5应用程序中,如果我使用CDN中的标头< script> 标签加载Bootstrap 4,一切正常.但是,当我将Bootstrap(及其依赖项)安装到 node_modules 并与Webpack一起使用时,它仍然可以正常工作……但是Bootstrap的jQuery方法应该像 $(foo)那样添加.modal() $(bar).popover()在JavaScript控制台中显示错误:

In my Rails 5 app, if I load Bootstrap 4 using a header <script> tag from a CDN, everything works fine. But when I install Bootstrap (and its dependencies) to node_modules, and serve it with Webpack, it mostly still works... but the jQuery methods Bootstrap is supposed to add like $(foo).modal() or $(bar).popover() give errors in the JavaScript console:

Uncaught TypeError: $(...).modal is not a function
Uncaught TypeError: $(...).popover is not a function

还有其他一些关于此类错误的StackOverflow问题,但是那里列出的解决方案都不适合我.最常见的原因似乎是jQuery被两次包含在内,但是我敢肯定我没有这么做.当我从 app/javascript/packs/application.js (参见下文)中删除jQuery import 时,所有jQuery都停止工作.jQuery不在我的 Gemfile 中,它是gem,而单词"jquery"仅出现在下面显示的文件中.

There are several other StackOverflow questions about errors like that, but none of the solutions listed there work for me. The most common cause seems to be jQuery getting included twice, but I'm pretty sure I'm not doing that; when I remove the jQuery import from app/javascript/packs/application.js (see below), then all of jQuery stops working. jQuery is not in my Gemfile as a gem, and the word "jquery" only appears in the files I've shown below.

我以正确的顺序加载(请参阅下文;在Bootstrap之前使用jQuery和Popper).我在方法调用周围使用了文档就绪的包装器(请参见下文),因此我不会过早地调用它们.Bootstrap CSS可以很好地加载,并且使用 data-toggle ="modal" 的DOM元素可以正确显示模式:

I'm loading in the correct order (see below; jQuery and Popper before Bootstrap). I'm using a document-ready wrapper around the method calls (see below), so I'm not calling them too soon. The Bootstrap CSS loads fine, and DOM elements using data-toggle="modal" display the modal correctly:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Show Modal
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <!- ... ->
    </div>
  </div>
</div>

...仅当在JS代码中调用诸如 $(foo).modal()等方法时出现错误:

...it's only when methods like $(foo).modal() etc. are called in JS code that I get the error:

<script>
  $(function () {
    $('#exampleModal').on('shown.bs.modal', function (e) {
      console.log('modal shown!');
    });
    $('#otherModalButton').click(function (e) {
      e.preventDefault();
      console.log('clicked!');
      $('#exampleModal').modal('show');  // <- "not a function" error
      return false;
    });
  });
</script>

我的设置:

Node.js v10.20.1
ruby 2.5.8p224 (2020-03-31 revision 67882) [x86_64-linux]
Rails 5.2.4.2

package.json:    "@rails/webpacker": "4.2.2",
package.json:    "bootstrap": "4.4.1",
package.json:    "jquery": "3.4.1",
package.json:    "popper.js": "1.16.1"
package.json:    "webpack-dev-server": "^3.11.0"

// config/webpack/development.js
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
const environment = require('./environment')
module.exports = environment.toWebpackConfig()

// config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.append(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',  // taking this out doesn't fix it
    Popper: ['popper.js', 'default']
  })
)
module.exports = environment

<!DOCTYPE html>
<!-- app/views/layouts/application.html.erb -->
<html>
  <head>
    [...]
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= javascript_pack_tag    'application' %>
    <%# if I load with these two lines (instead of in app/javascript/packs/application.js), it all works: %>
    <%# javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js' %>
    <%# javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js' %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

// app/javascript/packs/application.js
import 'jquery/src/jquery'
import 'popper.js/dist/esm/popper'
import 'bootstrap/dist/js/bootstrap'
import '../stylesheets/application'

// app/javascript/stylesheets/application.scss
@import "~bootstrap/scss/bootstrap";

我已经手动查看了 webpack-dev-server 正在生成的JS包;我在那里可以看到Bootstrap.控制台中的Webpack输出显示软件包已成功编译,没有错误.我已经在Chrome(ChromeOS和MacOS)和Firefox(MacOS)上都尝试过此操作.

I've manually reviewed the JS pack that webpack-dev-server is producing; I can see Bootstrap in there. The Webpack output in the console shows the pack successfully compiled with no errors. I've tried this on both Chrome (ChromeOS and MacOS) and Firefox (MacOS).

有什么可以尝试的想法吗?

Any ideas for what I can try?

推荐答案

问题是

new webpack.ProvidePlugin({
 $: 'jquery',
 jQuery: 'jquery',  // taking this out doesn't fix it
...

require"jquery" 导致jquery被加载两次.如果您检查已编译的application.js,则可能会看到它是必需的"./node_modules/jquery/dist/jquery.js" ,然后需要"之内的所有js文件.node_modules/jquery/"",一一尝试,搜索./node_modules/jquery/

and require "jquery" caused jquery to be loaded twice. if you check the compiled application.js, you may see it required "./node_modules/jquery/dist/jquery.js", and then required all js files inside "./node_modules/jquery/" one by one, try it, search ./node_modules/jquery/

您可以在小地图中看到很多结果!

As you can see in the minimap, so many results!

我的解决方案

我从 enviroments.js

 $: 'jquery',
 jQuery: 'jquery',  

并在applictions.js中将 require"jquery" 更改为

and in applictions.js change require "jquery" to

import JQuery from 'jquery';
window.$ = window.JQuery = JQuery;

这篇关于如果Bootstrap加载了Webpack(Rails),则modal()之类的方法将不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆