Skip to main content Skip to docs navigation

Bootstrap 和 Webpack

官方指南:如何使用 Webpack 在项目中引入和打包 Bootstrap 的 CSS 和 JavaScript。

想直接跳到最后吗?twbs/examples 仓库 下载本指南的源代码和可运行演示。你也可以 在 StackBlitz 中打开示例 进行实时编辑。

什么是 Webpack?

🌐 What is Webpack?

Webpack 是一个 JavaScript 模块打包工具,它处理模块及其依赖以生成静态资源。它简化了管理具有多个文件和依赖的复杂网页应用的过程。

设置

🌐 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.

  1. 创建一个项目文件夹并设置 npm。 我们将创建 my-project 文件夹,并使用 -y 参数初始化 npm,以避免它询问我们所有的交互式问题。

    mkdir my-project && cd my-project
    npm init -y
    
  2. 安装 Webpack。 接下来我们需要安装 Webpack 的开发依赖:用于 Webpack 核心的 webpack,用于在终端运行 Webpack 命令的 webpack-cli,以及用于运行本地开发服务器的 webpack-dev-server。此外,我们将安装 html-webpack-plugin,以便将我们的 index.html 存储在 src 目录中,而不是默认的 dist 目录。我们使用 --save-dev 来表示这些依赖仅用于开发,而不用于生产环境。

    npm i --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin
    
  3. 安装 Bootstrap。 现在我们可以安装 Bootstrap。我们还将安装 Popper,因为我们的下拉菜单、弹出框和工具提示依赖它来定位。如果你不打算使用这些组件,可以在此省略安装 Popper。

    npm i --save bootstrap @popperjs/core
    
  4. 安装额外的依赖。 除了 Webpack 和 Bootstrap,我们还需要一些额外的依赖,以便使用 Webpack 正确导入和打包 Bootstrap 的 CSS 和 JS。这些包括 Sass、一些加载器和 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。现在我们还将创建 srcdist 文件夹,以完善项目结构。从 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.

  1. 在你的编辑器中打开 webpack.config.js 由于它是空的,我们需要向其中添加一些模板配置,以便我们可以启动服务器。配置的这一部分告诉 Webpack 去哪里查找我们项目的 JavaScript、将编译后的代码输出到何处(dist),以及开发服务器应该如何运行(从 dist 文件夹获取并启用热重载)。

    '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' })
      ]
    }
    
  2. 接下来我们填写我们的 src/index.html 这是 Webpack 将在浏览器中加载的 HTML 页面,以使用我们将在后续步骤中添加到其中的打包 CSS 和 JS。在我们这样做之前,我们必须给它一些内容以渲染,并包含上一步的 output JS。

    <!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>
    

    我们在这里包括了一点 Bootstrap 样式,通过 div class="container"<button> 来显示何时 Bootstrap 的 CSS 被 Webpack 加载。

  3. 现在我们需要一个 npm 脚本来运行 Webpack。 打开 package.json 并添加下面显示的 start 脚本(你应该已经有了测试脚本)。我们将使用这个脚本来启动本地的 Webpack 开发服务器。你也可以添加下面显示的 build 脚本来构建你的项目。

    {
      // ...
      "scripts": {
        "start": "webpack serve",
        "build": "webpack build --mode=production",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      // ...
    }
    
  4. 最后,我们可以启动 Webpack。 在终端中从 my-project 文件夹运行新添加的 npm 脚本:

    npm start
    
    Webpack dev server running

在本指南的下一部分也是最后一部分中,我们将设置 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.

  1. webpack.config.js 中设置加载器。 你的配置文件现在已完成,并且应该与下面的片段匹配。这里唯一的新部分是 module 部分。

    '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',
                options: {
                  sassOptions: {
                    // Optional: Silence Sass deprecation warnings. See note below.
                    silenceDeprecations: [
                      'mixed-decls',
                      'color-functions',
                      'global-builtin',
                      'import'
                    ]
                  }
                }
              }
            ]
          }
        ]
      }
    }
    

    这是我们需要所有这些加载器的原因回顾。style-loader 将 CSS 注入到 HTML 页面 <head> 中的 <style> 元素中,css-loader 帮助使用 @importurl()postcss-loader 是 Autoprefixer 所必需的,sass-loader 允许我们使用 Sass。

    注意: 当使用最新版本的 Dart Sass 编译源 Sass 文件时,会显示 Sass 弃用警告。这不会阻止 Bootstrap 的编译或使用。我们正在努力寻找长期解决方案,但在此期间这些弃用通知可以忽略。

  2. 现在,让我们导入 Bootstrap 的 CSS。 将以下内容添加到 src/scss/styles.scss 以导入所有 Bootstrap 的源 Sass。

    // Import all of Bootstrap’s CSS
    @import "bootstrap/scss/bootstrap";
    

    如果你愿意,你也可以单独导入我们的样式表。阅读我们的 Sass 导入文档了解详情。

  3. 接下来我们加载 CSS 并导入 Bootstrap 的 JavaScript。 将以下内容添加到 src/js/main.js 以加载 CSS 并导入所有的 Bootstrap JS。Popper 将通过 Bootstrap 自动导入。

    // Import our custom CSS
    import '../scss/styles.scss'
    
    // Import all of Bootstrap’s JS
    import * as bootstrap from 'bootstrap'
    

    你还可以根据需要单独导入 JavaScript 插件,以缩小包大小:

    import Alert from 'bootstrap/js/dist/alert'
    
    // or, specify which plugins you need:
    import { Tooltip, Toast, Popover } from 'bootstrap'
    

    阅读我们的 JavaScript 文档 以获取有关如何使用 Bootstrap 插件的更多信息。

  4. 你完成了!🎉 当 Bootstrap 的源 Sass 和 JS 完全加载后,你的本地开发服务器现在应该看起来像这样:

    Webpack dev server running with Bootstrap

    现在你可以开始添加任何你想使用的 Bootstrap 组件。一定要查看完整的 Webpack 示例项目,了解如何包含额外的自定义 Sass,并通过仅导入你需要的 Bootstrap CSS 和 JS 部分来优化构建。

生产优化

🌐 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 中。你可以像这样在 dist/index.html 中包含生成的 CSS:

🌐 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.