更新为Webpacker 3.5.0 and [电子邮件受保护] /cdn-cgi/l/email-protection
Popper.js
and [email protected] /cdn-cgi/l/email-protection
不需要安装 JQuery。但是,Bootstrap 4 需要 JQuery 和 Popper.js,我认为这就是在原始示例中显示它们的目的。另外,我在示例中省略了 Vue,因为有足够的文档介绍如何添加 Vue 连接。
为了让一切正常工作,我安装了webpack-merge
, popper.js
, jquery
, jquery-ujs
, and [email protected] /cdn-cgi/l/email-protection
通过纱线。
安装后,我可以更新./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
Then in ./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
部分在./app/views/layouts/application.html.haml
显示Webpack内容:
= stylesheet_pack_tag 'application'
= javascript_pack_tag 'application'
制作完成后static_pages
控制器和static_pages#index
查看,启动 Rails 服务器后(rails s
),我能够进入浏览器的 JS 控制台并运行console.log(jQuery().jquery);
查看 JQuery 是否正在加载。一切都按预期加载。
文档可以在这里找到:https://github.com/rails/webpacker/blob/master/docs/webpack.md https://github.com/rails/webpacker/blob/master/docs/webpack.md