设置
¥Setup
我们正在从头开始使用 Bootstrap 构建一个 Webpack 项目,因此在我们真正开始之前,有一些先决条件和前期步骤。本指南要求你安装 Node.js 并熟悉终端。
¥We’re building a Webpack project with Bootstrap from scratch, so there are some prerequisites and upfront steps before we can really get started. This guide requires you to have Node.js installed and some familiarity with the terminal.
-
创建项目文件夹并设置 npm。我们将创建
my-project
文件夹并使用-y
参数初始化 npm,以避免它询问我们所有交互式问题。¥Create a project folder and set up npm. We’ll create the
my-project
folder and initialize npm with the-y
argument to avoid it asking us all the interactive questions.mkdir my-project && cd my-project npm init -y
-
安装 Webpack。接下来我们需要安装 Webpack 开发依赖:
webpack
是 Webpack 的核心,webpack-cli
使我们可以从终端运行 Webpack 命令,webpack-dev-server
使我们可以运行本地开发服务器。此外,我们将安装html-webpack-plugin
,以便能够将index.html
存储在src
目录中,而不是默认的dist
目录中。我们使用--save-dev
来表示这些依赖仅供开发使用,不适用于生产。¥Install Webpack. Next we need to install our Webpack development dependencies:
webpack
for the core of Webpack,webpack-cli
so we can run Webpack commands from the terminal, andwebpack-dev-server
so we can run a local development server. Additionally, we’ll installhtml-webpack-plugin
to be able to store ourindex.html
insrc
directory instead of the defaultdist
one. We use--save-dev
to signal that these dependencies are only for development use and not for production.npm i --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin
-
安装 Bootstrap。现在我们可以安装 Bootstrap 了。我们还将安装 Popper,因为我们的下拉菜单、弹出窗口和工具提示的定位依赖于它。如果你不打算使用这些组件,则可以在此处省略 Popper。
¥Install Bootstrap. Now we can install Bootstrap. We’ll also install Popper since our dropdowns, popovers, and tooltips depend on it for their positioning. If you don’t plan on using those components, you can omit Popper here.
npm i --save bootstrap @popperjs/core
-
安装额外的依赖。除了 Webpack 和 Bootstrap 之外,我们还需要一些依赖才能正确导入 Bootstrap 的 CSS 和 JS 并将其与 Webpack 打包在一起。其中包括 Sass、一些加载器和 Autoprefixer。
¥Install additional dependencies. In addition to Webpack and Bootstrap, we need a few more dependencies to properly import and bundle Bootstrap’s CSS and JS with Webpack. These include Sass, some loaders, and Autoprefixer.
npm i --save-dev autoprefixer css-loader postcss-loader sass sass-loader style-loader
现在我们已经安装了所有必要的依赖,我们可以开始创建项目文件并导入 Bootstrap。
¥Now that we have all the necessary dependencies installed, we can get to work creating the project files and importing Bootstrap.
项目结构
¥Project structure
我们已经创建了 my-project
文件夹并初始化了 npm。现在我们还将创建 src
和 dist
文件夹来完善项目结构。从 my-project
运行以下命令,或手动创建如下所示的文件夹和文件结构。
¥We’ve already created the my-project
folder and initialized npm. Now we’ll also create our src
and dist
folders to round out the project structure. Run the following from my-project
, or manually create the folder and file structure shown below.
mkdir {src,src/js,src/scss}
touch src/index.html src/js/main.js src/scss/styles.scss webpack.config.js
完成后,你的完整项目应如下所示:
¥When you’re done, your complete project should look like this:
my-project/
├── src/
│ ├── js/
│ │ └── main.js
│ ├── scss/
│ │ └── styles.scss
│ └── index.html
├── package-lock.json
├── package.json
└── webpack.config.js
此时,一切都在正确的位置,但是 Webpack 无法工作,因为我们还没有填写 webpack.config.js
。
¥At this point, everything is in the right place, but Webpack won’t work because we haven’t filled in our webpack.config.js
yet.
配置 Webpack
¥Configure Webpack
安装依赖并准备好项目文件夹以开始编码后,我们现在可以配置 Webpack 并在本地运行我们的项目。
¥With dependencies installed and our project folder ready for us to start coding, we can now configure Webpack and run our project locally.
-
在编辑器中打开
webpack.config.js
。由于它是空白的,我们需要向其中添加一些样板配置,以便我们可以启动我们的服务器。这部分配置告诉 Webpack 在哪里查找我们项目的 JavaScript、在哪里将编译后的代码输出到 (dist
),以及开发服务器应该如何运行(通过热重载从dist
文件夹中提取)。¥Open
webpack.config.js
in your editor. Since it’s blank, we’ll need to add some boilerplate config to it so we can start our server. This part of the config tells Webpack where to look for our project’s JavaScript, where to output the compiled code to (dist
), and how the development server should behave (pulling from thedist
folder with hot reload).'use strict' const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { mode: 'development', entry: './src/js/main.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist') }, devServer: { static: path.resolve(__dirname, 'dist'), port: 8080, hot: true }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ] }
-
接下来我们填写我们的
src/index.html
。这是 Webpack 将在浏览器中加载的 HTML 页面,以利用我们将在后续步骤中添加的打包 CSS 和 JS。在此之前,我们必须为其提供一些渲染内容并包含上一步中的output
JS。¥Next we fill in our
src/index.html
. This is the HTML page Webpack will load in the browser to utilize the bundled CSS and JS we’ll add to it in later steps. Before we can do that, we have to give it something to render and include theoutput
JS from the previous step.<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap w/ Webpack</title> </head> <body> <div class="container py-4 px-3 mx-auto"> <h1>Hello, Bootstrap and Webpack!</h1> <button class="btn btn-primary">Primary button</button> </div> </body> </html>
我们在此处使用
div class="container"
和<button>
添加了一些 Bootstrap 样式,以便我们可以看到 Webpack 何时加载 Bootstrap 的 CSS。¥We’re including a little bit of Bootstrap styling here with the
div class="container"
and<button>
so that we see when Bootstrap’s CSS is loaded by Webpack. -
现在我们需要一个 npm 脚本来运行 Webpack。打开
package.json
并添加如下所示的start
脚本(你应该已经有了测试脚本)。我们将使用此脚本来启动本地 Webpack 开发服务器。你还可以添加如下所示的build
脚本来构建你的项目。¥Now we need an npm script to run Webpack. Open
package.json
and add thestart
script shown below (you should already have the test script). We’ll use this script to start our local Webpack dev server. You can also add abuild
script shown below to build your project.{ // ... "scripts": { "start": "webpack serve", "build": "webpack build --mode=production", "test": "echo \"Error: no test specified\" && exit 1" }, // ... }
-
最后,我们可以启动 Webpack。从终端的
my-project
文件夹中,运行新添加的 npm 脚本:¥And finally, we can start Webpack. From the
my-project
folder in your terminal, run that newly added npm script:npm start
在本指南的下一部分也是最后一部分中,我们将设置 Webpack 加载器并导入所有 Bootstrap 的 CSS 和 JavaScript。
¥In the next and final section to this guide, we’ll set up the Webpack loaders and import all of Bootstrap’s CSS and JavaScript.
导入 Bootstrap
¥Import Bootstrap
将 Bootstrap 导入 Webpack 需要我们在第一部分中安装的加载器。我们已经使用 npm 安装了它们,但现在需要配置 Webpack 才能使用它们。
¥Importing Bootstrap into Webpack requires the loaders we installed in the first section. We’ve installed them with npm, but now Webpack needs to be configured to use them.
-
在
webpack.config.js
设置加载器。你的配置文件现已完成,并且应与下面的代码片段匹配。这里唯一的新部分是module
部分。¥Set up the loaders in
webpack.config.js
. Your configuration file is now complete and should match the snippet below. The only new part here is themodule
section.'use strict' const path = require('path') const autoprefixer = require('autoprefixer') const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { mode: 'development', entry: './src/js/main.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist') }, devServer: { static: path.resolve(__dirname, 'dist'), port: 8080, hot: true }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ], module: { rules: [ { test: /\.(scss)$/, use: [ { // Adds CSS to the DOM by injecting a `<style>` tag loader: 'style-loader' }, { // Interprets `@import` and `url()` like `import/require()` and will resolve them loader: 'css-loader' }, { // Loader for webpack to process CSS with PostCSS loader: 'postcss-loader', options: { postcssOptions: { plugins: [ autoprefixer ] } } }, { // Loads a SASS/SCSS file and compiles it to CSS loader: 'sass-loader' } ] } ] } }
这里回顾一下为什么我们需要所有这些加载器。
style-loader
将 CSS 注入到 HTML 页面的<head>
中的<style>
元素中,css-loader
有助于使用@import
和url()
,postcss-loader
是 Autoprefixer 所必需的,sass-loader
允许我们使用 Sass。¥Here’s a recap of why we need all these loaders.
style-loader
injects the CSS into a<style>
element in the<head>
of the HTML page,css-loader
helps with using@import
andurl()
,postcss-loader
is required for Autoprefixer, andsass-loader
allows us to use Sass. -
现在,让我们导入 Bootstrap 的 CSS。将以下内容添加到
src/scss/styles.scss
以导入所有 Bootstrap 的源 Sass。¥Now, let’s import Bootstrap’s CSS. Add the following to
src/scss/styles.scss
to import all of Bootstrap’s source Sass.// Import all of Bootstrap's CSS @import "bootstrap/scss/bootstrap";
如果需要,你还可以单独导入我们的样式表。Read our Sass import docs for details.
¥You can also import our stylesheets individually if you want. Read our Sass import docs for details.
-
接下来我们加载 CSS 并导入 Bootstrap 的 JavaScript。将以下内容添加到
src/js/main.js
以加载 CSS 并导入所有 Bootstrap 的 JS。Popper 将通过 Bootstrap 自动导入。¥Next we load the CSS and import Bootstrap’s JavaScript. Add the following to
src/js/main.js
to load the CSS and import all of Bootstrap’s JS. Popper will be imported automatically through Bootstrap.// Import our custom CSS import '../scss/styles.scss' // Import all of Bootstrap's JS import * as bootstrap from 'bootstrap'
你还可以根据需要单独导入 JavaScript 插件,以缩小包大小:
¥You can also import JavaScript plugins individually as needed to keep bundle sizes down:
import Alert from 'bootstrap/js/dist/alert' // or, specify which plugins you need: import { Tooltip, Toast, Popover } from 'bootstrap'
Read our JavaScript docs for more information on how to use Bootstrap’s plugins.
-
你就完成了!🎉 当 Bootstrap 的源 Sass 和 JS 完全加载后,你的本地开发服务器现在应该如下所示:
¥And you’re done! 🎉 With Bootstrap’s source Sass and JS fully loaded, your local development server should now look like this:
现在你可以开始添加你想要使用的任何 Bootstrap 组件。请务必了解 查看完整的 Webpack 示例项目,了解如何包含其他自定义 Sass 并通过仅导入你需要的 Bootstrap CSS 和 JS 部分来优化你的构建。
¥Now you can start adding any Bootstrap components you want to use. Be sure to check out the complete Webpack example project for how to include additional custom Sass and optimize your build by importing only the parts of Bootstrap’s CSS and JS that you need.
生产优化
¥Production optimizations
根据你的设置,你可能需要实现一些额外的安全性和速度优化,这对于在生产中运行项目很有用。请注意,这些优化不适用于 Webpack 示例项目,需要你自行实现。
¥Depending on your setup, you may want to implement some additional security and speed optimizations useful for running the project in production. Note that these optimizations are not applied on the Webpack example project and are up to you to implement.
提取 CSS
¥Extracting CSS
我们上面配置的 style-loader
可以方便地将 CSS 发送到打包包中,因此无需在 dist/index.html
中手动加载 CSS 文件。但是,此方法可能不适用于严格的内容安全策略,并且由于打包包大小较大,它可能会成为应用的瓶颈。
¥The style-loader
we configured above conveniently emits CSS into the bundle so that manually loading a CSS file in dist/index.html
isn’t necessary. This approach may not work with a strict Content Security Policy, however, and it may become a bottleneck in your application due to the large bundle size.
要分离 CSS 以便我们可以直接从 dist/index.html
加载它,请使用 mini-css-extract-loader
Webpack 插件。
¥To separate the CSS so that we can load it directly from dist/index.html
, use the mini-css-extract-loader
Webpack plugin.
首先,安装插件:
¥First, install the plugin:
npm install --save-dev mini-css-extract-plugin
然后在 Webpack 配置中实例化并使用该插件:
¥Then instantiate and use the plugin in the Webpack configuration:
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -3,6 +3,7 @@
const path = require('path')
const autoprefixer = require('autoprefixer')
const HtmlWebpackPlugin = require('html-webpack-plugin')
+const miniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
mode: 'development',
@@ -17,7 +18,8 @@ module.exports = {
hot: true
},
plugins: [
- new HtmlWebpackPlugin({ template: './src/index.html' })
+ new HtmlWebpackPlugin({ template: './src/index.html' }),
+ new miniCssExtractPlugin()
],
module: {
rules: [
@@ -25,8 +27,8 @@ module.exports = {
test: /\.(scss)$/,
use: [
{
- // Adds CSS to the DOM by injecting a `<style>` tag
- loader: 'style-loader'
+ // Extracts CSS for each JS file that includes CSS
+ loader: miniCssExtractPlugin.loader
},
{
再次运行 npm run build
后,会出现一个新文件 dist/main.css
,其中包含 src/js/main.js
导入的所有 CSS。如果你现在在浏览器中查看 dist/index.html
,样式将会丢失,就像现在在 dist/main.css
中一样。你可以将生成的 CSS 包含在 dist/index.html
中,如下所示:
¥After running npm run build
again, there will be a new file dist/main.css
, which will contain all of the CSS imported by src/js/main.js
. If you view dist/index.html
in your browser now, the style will be missing, as it is now in dist/main.css
. You can include the generated CSS in dist/index.html
like this:
--- a/dist/index.html
+++ b/dist/index.html
@@ -3,6 +3,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
+ <link rel="stylesheet" href="./main.css">
<title>Bootstrap w/ Webpack</title>
</head>
<body>
提取 SVG 文件
¥Extracting SVG files
Bootstrap 的 CSS 包含通过内联 data:
URI 对 SVG 文件的多个引用。如果你为项目定义了阻止图片的 data:
URI 的内容安全策略,则这些 SVG 文件将不会加载。你可以通过使用 Webpack 的资源模块功能提取内联 SVG 文件来解决此问题。
¥Bootstrap’s CSS includes multiple references to SVG files via inline data:
URIs. If you define a Content Security Policy for your project that blocks data:
URIs for images, then these SVG files will not load. You can get around this problem by extracting the inline SVG files using Webpack’s asset modules feature.
配置 Webpack 以提取内联 SVG 文件,如下所示:
¥Configure Webpack to extract inline SVG files like this:
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -23,6 +23,14 @@ module.exports = {
},
module: {
rules: [
+ {
+ mimetype: 'image/svg+xml',
+ scheme: 'data',
+ type: 'asset/resource',
+ generator: {
+ filename: 'icons/[hash].svg'
+ }
+ },
{
test: /\.(scss)$/,
use: [
再次运行 npm run build
后,你会发现 SVG 文件被提取到 dist/icons
中并从 CSS 中正确引用。
¥After running npm run build
again, you’ll find the SVG files extracted into dist/icons
and properly referenced from CSS.
See something wrong or out of date here? Please open an issue on GitHub. Need help troubleshooting? Search or start a discussion on GitHub.