必须用 Sass 源码编译才能实现真正按需加载,因为 bootstrap.min.css 是全量编译产物,无法动态剔除未用样式;只有在构建期通过按序导入 functions→variables→mixins 及所需模块,并配合 $enable-* 变量禁用冗余功能,才能将 CSS 体积压至 20–40KB。

必须用 Sass 源码编译,不能直接改 bootstrap.min.css
Bootstrap 5 官方不提供“开箱即用”的按需 CSS 加载机制。你看到的 bootstrap/dist/css/bootstrap.min.css 是全量构建产物,无论删哪行、注释哪段,都不算真正按需——它已经编译完成,再修改只是徒增维护成本,还容易破坏样式依赖链。
真正可控的按需,只发生在 Sass 编译阶段:从 node_modules/bootstrap/scss/ 下一个个 @import 你需要的模块,跳过不需要的(比如 carousel、tooltip),让编译器只处理被引用的部分。
导入顺序不能乱:functions → variables → mixins → 其他
Bootstrap 的 Sass 模块之间有强依赖。比如 utilities 里大量用到 map-get($theme-colors, primary),而 $theme-colors 来自 variables,map-get 是内置函数——这些都得提前就位。
所以你的自定义 .scss 文件开头必须严格按这个顺序写:
@import "bootstrap/scss/functions"; @import "bootstrap/scss/variables"; @import "bootstrap/scss/mixins"; @import "bootstrap/scss/utilities"; @import "bootstrap/scss/components/buttons"; @import "bootstrap/scss/layout/container";
漏掉 functions 或调换 variables 和 mixins,编译会报错,常见错误信息像:Error: Undefined variable: "$enable-rounded" 或 Function "color-contrast" not found。
禁用默认工具类要靠 $enable-* 变量控制
光是不 @import utilities 不够——如果你导入了 components/buttons,它内部会悄悄拉入部分 utilities(比如 spacing、display)。更稳妥的方式是保留 utilities 导入,但关掉不需要的子集:
- 在
@import "bootstrap/scss/variables"之后、@import "bootstrap/scss/utilities"之前,覆盖变量:
$enable-shadows: false; $enable-gradients: false; $enable-transitions: true; $enable-grid-classes: true; $enable-button-classes: true; $enable-container-classes: true;
这些开关能精准剔除对应 CSS 规则,比手动删文件或靠 PurgeCSS 更底层、更可靠。注意:$enable-* 必须在 utilities 导入前生效,否则无效。
构建工具要能解析 node_modules 中的 Bootstrap 路径
Vite 默认支持 @import "bootstrap/scss/functions" 这种写法;Webpack 则需要确认 sass-loader 配置中 additionalData 或 includePaths 包含 node_modules,否则会报 File to import not found。
常见卡点:
- Vite 项目里没装
sass(不是node-sass):运行npm install -D sass - Webpack + sass-loader 未配置
includePaths: ["node_modules"] - 路径写成
@import "./node_modules/bootstrap/scss/functions"(多加了./,导致相对路径查找失败)
最终生成的 CSS 体积是否真的变小,最简单的验证方式是:打开浏览器开发者工具 → Network → 找到你引入的 CSS 文件 → 看 size 是否落到 20–40KB 区间(仅含 grid、buttons、container 等基础模块时)。如果还是 190KB 左右,说明根本没走 Sass 编译流程,还在用 dist/css 的全量包。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











