将 Bootstrap 与 Webpack 结合使用



我有一个使用 Webpack 的应用程序。我是 Webpack 的新手,并试图学习如何有效地使用它。具体来说,我正在尝试将带有Font Awesome的Bootstrap导入我的项目中。我找到了这个SO帖子,但是,我仍然无法使用Bootstrap。我不确定它是否已经过时,或者我是否误解了某些内容。

我尝试通过网址加载器加载Bootstrap和Font Awesome。我引用了以下网址:

https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css
https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css

我还尝试通过 NPM 加载 Bootstrap 和 Font Awesome,然后在我的入口文件中引用它,如下所示:

require('bootstrap');
require('font-awesome');

似乎这应该是常用模板的一部分。但是,我没有找到。如何在 Webpack 中使用 Bootstrap 和 Font Awesome?

但是,我也对这种方法有所欠缺。

我在GitHub上创建了一个简单的例子。使用 Webpack 2 和 Bootstrap 3。

安装依赖项npm install jquery bootstrap

索引.js

require('bootstrap');
require('bootstrap/dist/css/bootstrap.css');
require('font-awesome/css/font-awesome.css'); //Optional. The question author uses this package.

网络包

const webpack = require('webpack');
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: path.resolve(__dirname, "index.js"),
output: {
path: path.resolve(__dirname, 'dist'),
filename: "bundle.js"
},
module: {
rules: [    
{
test: /.woff2?$|.ttf$|.eot$|.svg$/,
use: [{
loader: "file-loader"
}]
},
{
test: /.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
}
]
},
plugins: [
new ExtractTextPlugin('bundle.styles.css'),
new webpack.ProvidePlugin({
// inject ES5 modules as global vars
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
})
]
};

索引.html

<link rel="stylesheet" type="text/css" href="/dist/bundle.styles.css">
<script type="text/javascript" src="/dist/bundle.js"></script>

如果不想手动插入bundle.styles.cssbundle.js,可以使用HtmlWebpackPlugin

如果您不是动态生成基本 HTML 文件,那么您可以在基本 HTML 的 head 部分中符号包含一个<link>标记(意味着到处都是相同的基本 HTML 文件(

如果你想使用 webpack 使用它,那么除了 url-loader 之外,你需要使用style-loadercss-loader(如果你想插入样式作为style标签在 Head Witch 中可能不是这样(

或者你可以使用 webpack 的extract to text插件作为不同的文件加载并使用 HTMLlink标签插入它

作为参考,您可以使用此开源项目的配置文件

网络包生产配置

webpack 开发配置

编辑:链接更新

最新更新