Webpack and bundlersWebpack和捆绑版
Learn how to include Bootstrap in your project using Webpack or other bundlers.了解如何使用Webpack或其他绑定器在项目中包括Bootstrap。
Installing Bootstrap安装Bootstrap程序
Install bootstrap as a Node.js module using npm.使用npm将Bootstrap安装为Node.js模块。
Importing 导入JavaScript
Import Bootstrap’s JavaScript by adding this line to your app’s entry point (usually 通过将此行添加到应用程序的入口点(通常为index.js
or app.js
):index.js
或app.js
),导入Bootstrap程序的JavaScript:
// You can specify which plugins you need
import { Tooltip, Toast, Popover } from 'bootstrap';
Alternatively, if you only need just a few of our plugins, you may import plugins individually as needed:或者,如果您只需要我们的几个插件,您可以根据需要单独导入插件:
import Alert from 'bootstrap/js/dist/alert';
...
Bootstrap depends on Popper, which is specified in the peerDependencies
property.
This means that you will have to make sure to add it to your package.json
using npm install @popperjs/core
.
Importing Styles导入样式
Importing Precompiled Sass导入预编译的Sass
To enjoy the full potential of Bootstrap and customize it to your needs, use the source files as a part of your project’s bundling process.要充分发挥Bootstrap的潜力并根据您的需要对其进行定制,请将源文件用作项目捆绑过程的一部分。
First, create your own 首先,创建自己的_custom.scss
and use it to override the built-in custom variables. custom.scss
并使用它覆盖内置的自定义变量。Then, use your main Sass file to import your custom variables, followed by Bootstrap:然后,使用主Sass文件导入自定义变量,然后导入Bootstrap:
@import "custom";
@import "~bootstrap/scss/bootstrap";
For Bootstrap to compile, make sure you install and use the required loaders: sass-loader, postcss-loader with Autoprefixer. 要编译Bootstrap程序,请确保安装并使用所需的加载程序:sass-loader、带Autoprefixer的postcss-loader。With minimal setup, your webpack config should include this rule or similar:通过最少的设置,您的网页包配置应包括以下规则或类似规则:
// ...
{
test: /\.(scss)$/,
use: [{
// inject CSS to page
loader: 'style-loader'
}, {
// translates CSS into CommonJS modules
loader: 'css-loader'
}, {
// Run postcss actions
loader: 'postcss-loader',
options: {
// `postcssOptions` is needed for postcss 8.x;
// if you use postcss 7.x skip the key
postcssOptions: {
// postcss plugins, can be exported to postcss.config.js
plugins: function () {
return [
require('autoprefixer')
];
}
}
}
}, {
// compiles Sass to CSS
loader: 'sass-loader'
}]
}
// ...
Importing Compiled CSS导入已编译的CSS
Alternatively, you may use Bootstrap’s ready-to-use CSS by simply adding this line to your project’s entry point:或者,您可以使用Bootstrap的即用CSS,只需将以下行添加到项目的入口点:
import 'bootstrap/dist/css/bootstrap.min.css';
In this case you may use your existing rule for 在这种情况下,您可以使用现有的css
without any special modifications to webpack config, except you don’t need sass-loader
just style-loader and css-loader.css
规则,而无需对webpack配置进行任何特殊修改,除非您不需要sass-loader
,只需要style-loader和css-loader。
// ...
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
]
}
// ...