直接@import "bootstrap/scss/bootstrap"会导致体积失控,因无差别加载全部组件、断点及工具类变体,sass无tree-shaking,实测多出约180kb;必须按functions→variables→mixins顺序导入前置模块,且$enable-*变量需在variables前定义以禁用无关功能。

为什么直接 @import "bootstrap/scss/bootstrap" 会导致体积失控
这行代码会无差别加载全部组件、全部断点、全部工具类变体(比如 mt-1 到 mt-xl-5、fw-light 到 fw-bolder),哪怕你只用了 btn 和 container。Sass 编译器不会做 tree-shaking,它只拼接所有 @import 内容,输出完整 CSS。实测全量引入比按需多出约 180KB。
必须前置导入的三个 Sass 模块顺序不能错
跳过任一模块或顺序颠倒,轻则样式错乱,重则编译失败:
-
@import "bootstrap/scss/functions";—— 所有map-get、color-contrast等函数依赖它 -
@import "bootstrap/scss/variables";—— 组件样式依赖$primary、$grid-columns等变量 -
@import "bootstrap/scss/mixins";——button-variant()、media-breakpoint-up()全靠它
注意:_variables.scss 中大量使用 !default,你必须在它之前定义同名变量才能覆盖,默认值才不会生效。
$enable-* 变量不是“开关”而是“编译指令”
设 $enable-modal: false 不是隐藏 modal,而是让编译器跳过生成 modal 相关的全部 CSS 和 JS 逻辑。不改这个,光删 @import "bootstrap/scss/modal" 可能无效——因为 tooltip 或 dropdown 会隐式拉入它。
- 在
@import "bootstrap/scss/variables"之前写:$enable-dropdown: false;、$enable-tooltip: false;、$enable-carousel: false; - 禁用表单图标:
$enable-form-validation-icons: false; - 搜
node_modules/bootstrap/scss/_variables.scss里所有以$enable-开头的变量,按需关闭
utilities 工具类是体积最大黑洞,别默认全开
默认开启全部断点 + 全部间距/颜色/阴影变体,utilities 单独就能贡献 40KB+ CSS。它不像组件可逐个关,得靠变量精细控制:
- 精简断点:
$grid-breakpoints: (xs: 0, md: 768px, xl: 1200px);(删掉sm和lg) - 收缩间距范围:
$spacers: (0: 0, 2: .5rem, 4: 1rem, 6: 1.5rem);(跳过1、3、5等中间值) - 禁用整类工具:
$enable-negative-margins: false;、$enable-shadows: false;
真正生效的前提:这些变量必须在 @import "bootstrap/scss/variables" 之前赋值,且不能带 !default;否则会被源文件里的默认值覆盖。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











