为Webpacker 3.5.0和bootstrap@4.1.1更新
Popper.js
并且bootstrap@4.0.0
不需要安装 JQuery。但是,Bootstrap 4 需要 JQuery 和 Popper.js,我认为这是在原始示例中展示它们的重点。此外,我在示例中省略了 Vue,因为有大量文档说明如何添加 Vue 连接。
为了让一切正常工作,我安装了webpack-merge
, popper.js
, jquery
, jquery-ujs
, 和bootstrap@4.1.1
via Yarn。
安装后,我可以./config/webpack/environment.js
使用以下代码进行更新:
/*
./config/webpack/environment.js
Info for this file can be found
github.com/rails/webpacker/blob/master/docs/webpack.md
*/
const { environment } = require('@rails/webpacker')
const merge = require('webpack-merge')
const webpack = require('webpack')
// Add an additional plugin of your choosing : ProvidePlugin
environment.plugins.prepend('Provide', new webpack.ProvidePlugin({
$: 'jquery',
JQuery: 'jquery',
jquery: 'jquery',
'window.Tether': "tether",
Popper: ['popper.js', 'default'], // for Bootstrap 4
})
)
const envConfig = module.exports = environment
const aliasConfig = module.exports = {
resolve: {
alias: {
jquery: 'jquery/src/jquery'
}
}
}
module.exports = merge(envConfig.toWebpackConfig(), aliasConfig)
现在envConfig.toWebpackConfig()
在 中的最后一条语句中使用了它,environment.js
我需要将 , 更改development.js
为以下内容:production.js
test.js
const environment = require('./environment')
module.exports = environment
然后在./app/javascript/application.js
我添加了以下内容:
// ./app/javascript/application.js
/* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb
console.log('Hello World from Webpacker')
// JS libraries
import "jquery"
import "jquery-ujs"
import "bootstrap"
为了确保 JQuery 没有通过资产管道加载,我删除了 Rails 资产连接./app/assets/javascripts/application.js
:
// require rails-ujs
// require_tree .
然后,我将这两行添加到header
in 部分./app/views/layouts/application.html.haml
以显示 Webpack 内容:
= stylesheet_pack_tag 'application'
= javascript_pack_tag 'application'
在创建static_pages
控制器和视图之后,在static_pages#index
启动 Rails 服务器rails s
(console.log(jQuery().jquery);
一切都按预期加载。
文档可以在这里找到:https ://github.com/rails/webpacker/blob/master/docs/webpack.md