Bootstrap JS 函数未在 Rails 6/Webpacker 中加载 [英] Bootstrap JS functions not loading in Rails 6/Webpacker
问题描述
通过 Webpacker 和 Rails 6 攀登学习曲线.
Climbing the learning curve with Webpacker and Rails 6.
我已经使用 Yarn 和 Webpacker 安装了 Boostrap 4.当我尝试在浏览器的 JS 控制台中使用 Bootstrap 组件时,我得到:TypeError: $.fn.button is undefined
.
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
.
如果我删除 Yarn 安装,在 HTML 的 head
中添加一个 Bootstrap CDN 链接(旧方式),一切正常.当我删除 CDN 链接并恢复使用 Webpacker 时,我又回到了上面的错误.
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.
这是我的 Webpacker 设置:
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'
我应该做些什么来将 Bootstrap 函数导出到全局命名空间?
Is there something I should be doing to export the Bootstrap functions to the global namespace?
推荐答案
找到了一个讨论这个问题的论坛:https://gorails.com/forum/how-to-use-bootstrap-with-webpack-rails-discussion
Found a forum where this was discussed: https://gorails.com/forum/how-to-use-bootstrap-with-webpack-rails-discussion
他们提到这可能是由于多次加载 jQuery 而导致的,最新的声明阻止了 Bootstrap 的 JS 加载.我在我的项目中找不到任何证据.
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.
对我来说,修复最终是在 webpack 入口点添加几行,将 jQuery 暴露给浏览器:
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;
这篇关于Bootstrap JS 函数未在 Rails 6/Webpacker 中加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!