[英]Using Webpack with jQuery and Bootstrap 4
I feel like there should be a straight-up example of this somewhere online.我觉得应该在网上某处有一个直接的例子。 Unfortunately, I've been unsuccessful in finding one.
不幸的是,我一直没有成功找到一个。 In short, I'm importing Bootstrap 4 via Yarn.
简而言之,我正在通过 Yarn 导入 Bootstrap 4。 One of the dependencies of Bootstrap 4 is jQuery.
Bootstrap 4 的依赖项之一是 jQuery。 These two dependencies will be used on all pages in my app.
这两个依赖项将用于我的应用程序中的所有页面。 For that reason, I wanted to bundle them together via Webpack.
出于这个原因,我想通过 Webpack 将它们捆绑在一起。 Currently, I have the following:
目前,我有以下几点:
app.js应用程序.js
// Import jQuery
const $ = require('jquery');
// Import Bootstrap
require('bootstrap/dist/css/bootstrap.min.css');
Then, in my webpack.config.js file, I have the following:然后,在我的 webpack.config.js 文件中,我有以下内容:
webpack.config.js webpack.config.js
"use strict";
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
app: './src/js/app.js',
},
plugins: [
new webpack.ProvidePlugin({$: 'jquery', jQuery: 'jquery' }),
new webpack.optimize.CommonsChunkPlugin({ name: 'common' }),
new webpack.optimize.UglifyJsPlugin()
],
output: {
publicPath: "/js/",
path: path.join(__dirname, '/dist/js/'),
filename: '[name].bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /(node_modules)/,
query: {
presets: ['es2015']
}
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader']
},
]
},
}
However, when I visit a webpack in my page, I see the following error:但是,当我在页面中访问 webpack 时,看到以下错误:
Uncaught ReferenceError: jQuery is not defined Uncaught ReferenceError: $ is not defined未捕获的 ReferenceError:未定义 jQuery 未捕获的 ReferenceError:未定义 $
How do I bundle jQuery and Bootstrap in my app via Webpack?如何通过 Webpack 在我的应用程序中捆绑 jQuery 和 Bootstrap?
As @rick-van-osta pointed out: you don't need to require jquery since you already loaded it via the provide plugin (this will create the global variable $ ):正如@rick-van-osta 指出的那样:您不需要需要 jquery,因为您已经通过提供插件加载了它(这将创建全局变量$ ):
new webpack.ProvidePlugin({$: 'jquery', jQuery: 'jquery' }),
remove the line const $ = require('jquery');
删除行
const $ = require('jquery');
from your app.js and you should be good to go.从你的 app.js 开始,你应该很高兴。
there is a webpack entry in the bootstrap documentation btw顺便说一下,引导程序文档中有一个webpack 条目
also since you are using node_modules, you should be able to change your app.js to:此外,由于您使用的是 node_modules,您应该能够将 app.js 更改为:
require('bootstrap');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.