bootstrap-webpack

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Bootstrap 6 with Webpack

使用 Webpack 搭建 Bootstrap 6 项目

Set up a Bootstrap 6 project bundled with Webpack, including the loaders needed to process Sass. Requires Node.js and terminal familiarity.
搭建一个通过 Webpack 打包的 Bootstrap 6 项目,包含处理 Sass 所需的各类 loader。需要具备 Node.js 基础和终端使用经验。

Workflow

工作流程

  • Step 1: Set up npm and install dependencies
  • Step 2: Create the project structure
  • Step 3: Configure Webpack (boilerplate + dev server)
  • Step 4: Set up loaders and import Bootstrap
  • Step 5: Verify
  • Step 6 (optional): Production optimizations

  • 步骤 1:配置 npm 并安装依赖
  • 步骤 2:创建项目结构
  • 步骤 3:配置 Webpack(基础模板 + dev server)
  • 步骤 4:配置 loader 并引入 Bootstrap
  • 步骤 5:验证配置
  • 步骤 6(可选):生产环境优化

Step 1: Set up npm and install dependencies

步骤 1:配置 npm 并安装依赖

  1. Create the project and initialize npm:
    sh
    mkdir my-project && cd my-project
    npm init -y
  2. Install Webpack and its tooling:
    sh
    npm i --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin
  3. Install Bootstrap and its optional peer dependencies (omit
    @floating-ui/dom
    if not using menus/popovers/tooltips; omit
    vanilla-calendar-pro
    if not using the datepicker):
    sh
    npm i --save bootstrap@6.0.0-alpha.1 @floating-ui/dom vanilla-calendar-pro
  4. Install the loaders and Sass/Autoprefixer needed to bundle Bootstrap's CSS:
    sh
    npm i --save-dev autoprefixer css-loader postcss-loader sass sass-loader style-loader

  1. 创建项目并初始化 npm:
    sh
    mkdir my-project && cd my-project
    npm init -y
  2. 安装 Webpack 及其相关工具:
    sh
    npm i --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin
  3. 安装 Bootstrap 及其可选 peer 依赖(如果不使用菜单/弹出框/工具提示,可省略
    @floating-ui/dom
    ;如果不使用日期选择器,可省略
    vanilla-calendar-pro
    ):
    sh
    npm i --save bootstrap@6.0.0-alpha.1 @floating-ui/dom vanilla-calendar-pro
  4. 安装打包 Bootstrap CSS 所需的 loader 以及 Sass/Autoprefixer:
    sh
    npm i --save-dev autoprefixer css-loader postcss-loader sass sass-loader style-loader

Step 2: Create the project structure

步骤 2:创建项目结构

sh
mkdir {src,src/js,src/scss}
touch src/index.html src/js/main.js src/scss/styles.scss webpack.config.js
Target layout:
text
my-project/
├── src/
│   ├── js/
│   │   └── main.js
│   ├── scss/
│   │   └── styles.scss
│   └── index.html
├── package-lock.json
├── package.json
└── webpack.config.js

sh
mkdir {src,src/js,src/scss}
touch src/index.html src/js/main.js src/scss/styles.scss webpack.config.js
目标目录结构:
text
my-project/
├── src/
│   ├── js/
│   │   └── main.js
│   ├── scss/
│   │   └── styles.scss
│   └── index.html
├── package-lock.json
├── package.json
└── webpack.config.js

Step 3: Configure Webpack

步骤 3:配置 Webpack

  1. webpack.config.js
    — entry, output, and dev server:
    js
    '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
    :
    html
    <!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-solid theme-primary">Primary button</button>
        </div>
      </body>
    </html>
  3. package.json
    — add scripts:
    json
    {
      "scripts": {
        "start": "webpack serve",
        "build": "webpack build --mode=production",
        "test": "echo \"Error: no test specified\" && exit 1"
      }
    }
  4. Start Webpack:
    sh
    npm start

  1. webpack.config.js
    —— 入口、输出与 dev server 配置:
    js
    '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
    :
    html
    <!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-solid theme-primary">Primary button</button>
        </div>
      </body>
    </html>
  3. package.json
    —— 添加脚本命令:
    json
    {
      "scripts": {
        "start": "webpack serve",
        "build": "webpack build --mode=production",
        "test": "echo \"Error: no test specified\" && exit 1"
      }
    }
  4. 启动 Webpack:
    sh
    npm start

Step 4: Set up loaders and import Bootstrap

步骤 4:配置 loader 并引入 Bootstrap

  1. Add the
    module.rules
    loader chain to
    webpack.config.js
    (order matters:
    sass-loader
    compiles,
    postcss-loader
    runs Autoprefixer,
    css-loader
    resolves imports,
    style-loader
    injects CSS):
    js
    '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: [
              { loader: 'style-loader' },
              { loader: 'css-loader' },
              {
                loader: 'postcss-loader',
                options: {
                  postcssOptions: {
                    plugins: [
                      autoprefixer
                    ]
                  }
                }
              },
              { loader: 'sass-loader' }
            ]
          }
        ]
      }
    }
  2. src/scss/styles.scss
    — import the source Sass with
    @use
    (never
    @import
    ):
    scss
    // Import all of Bootstrap's CSS
    @use "bootstrap/scss/bootstrap";
    To customize, override Bootstrap's CSS token maps (
    $root-tokens
    ,
    $*-tokens
    ) — see Customize › Sass. Token names are written unprefixed in Sass; Bootstrap's dist/CDN CSS adds the
    --bs-
    prefix via PostCSS, so compiling the source yourself keeps them unprefixed.
  3. src/js/main.js
    — load the CSS and import Bootstrap's JS. Floating UI and Vanilla Calendar Pro are imported automatically through Bootstrap:
    js
    // Import our custom CSS, then all of Bootstrap’s JS
    import '../scss/styles.scss'
    import * as bootstrap from 'bootstrap'
    Import only the plugins you need to keep bundle sizes down:
    js
    import { Tooltip, Toast, Popover } from 'bootstrap'

  1. 在
    webpack.config.js
    中添加
    module.rules
    loader 链(顺序很重要:
    sass-loader
    负责编译,
    postcss-loader
    运行 Autoprefixer,
    css-loader
    解析导入,
    style-loader
    注入 CSS):
    js
    '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: [
              { loader: 'style-loader' },
              { loader: 'css-loader' },
              {
                loader: 'postcss-loader',
                options: {
                  postcssOptions: {
                    plugins: [
                      autoprefixer
                    ]
                  }
                }
              },
              { loader: 'sass-loader' }
            ]
          }
        ]
      }
    }
  2. src/scss/styles.scss
    —— 使用
    @use
    引入 Sass 源文件(切勿使用
    @import
    ):
    scss
    // Import all of Bootstrap's CSS
    @use "bootstrap/scss/bootstrap";
    如需自定义样式,可覆盖 Bootstrap 的 CSS token 映射(
    $root-tokens
    、
    $*-tokens
    )—— 参见 自定义 › Sass。Sass 中的 token 名称没有前缀;Bootstrap 的发行版/CDN CSS 会通过 PostCSS 添加
    --bs-
    前缀,因此自行编译源文件时 token 不带此前缀。
  3. src/js/main.js
    —— 加载 CSS 并引入 Bootstrap 的 JS。Floating UI 和 Vanilla Calendar Pro 会通过 Bootstrap 自动引入:
    js
    // Import our custom CSS, then all of Bootstrap’s JS
    import '../scss/styles.scss'
    import * as bootstrap from 'bootstrap'
    如需减小打包体积,可仅引入你需要的插件:
    js
    import { Tooltip, Toast, Popover } from 'bootstrap'

Step 5: Verify

步骤 5:验证配置

  1. Run
    npm start
    and open
    http://localhost:8080
    — the
    .container
    and
    .btn-solid.theme-primary
    button should be styled.
  2. Confirm the console is free of module-resolution or loader errors.
  3. Trigger a JS component (tooltip/dialog) to confirm the JS bundle works.
  4. Bootstrap 6 requires a browser that supports
    oklch()
    and
    color-mix()
    .

  1. 运行
    npm start
    并打开
    http://localhost:8080
    ——
    .container
    容器和
    .btn-solid.theme-primary
    按钮应已应用样式。
  2. 确认控制台没有模块解析或 loader 相关错误。
  3. 触发一个 JS 组件(如 tooltip/对话框),确认 JS 打包文件正常运行。
  4. Bootstrap 6 需要浏览器支持
    oklch()
    和
    color-mix()
    。

Step 6 (optional): Production optimizations

步骤 6(可选):生产环境优化

Not required for a working setup; apply only if needed.
  • Extract CSS to a file (for strict CSP or to avoid a large JS bundle): install
    mini-css-extract-plugin
    , replace
    style-loader
    with
    miniCssExtractPlugin.loader
    , add the plugin, then link the generated
    dist/main.css
    from your HTML.
  • Extract inline SVGs: Bootstrap's CSS references SVGs via inline
    data:
    URIs. If your CSP blocks
    data:
    images, add a Webpack asset-module rule matching
    mimetype: 'image/svg+xml'
    /
    scheme: 'data'
    with
    type: 'asset/resource'
    to emit them as files.
For a complete reference, see the twbs/examples Webpack project.
这部分不是正常运行的必要配置,仅在需要时应用。
  • 将 CSS 提取为独立文件(适用于严格 CSP 或避免 JS 包体积过大的场景):安装
    mini-css-extract-plugin
    ,将
    style-loader
    替换为
    miniCssExtractPlugin.loader
    ,添加该插件,然后在 HTML 中链接生成的
    dist/main.css
    文件。
  • 提取内联 SVG:Bootstrap 的 CSS 通过内联
    data:
    URI 引用 SVG。如果你的 CSP 阻止
    data:
    图片,可添加一条 Webpack asset-module 规则,匹配
    mimetype: 'image/svg+xml'
    /
    scheme: 'data'
    并设置
    type: 'asset/resource'
    ,将它们输出为独立文件。
完整参考示例请参见 twbs/examples 中的 Webpack 项目。