Contents

Vite 使用 Bootstrap 5

使用小記

建立 Vite 專案

1
2
3
npm create vite@latest my-project -- --template vue
cd my-project
npm install

安裝 Bootstrap 5 和 Sass

1
2
3
npm install bootstrap
npm install sass -D
npm install @popperjs/core
  • bootstrap:Bootstrap 5 核心(含 CSS 和 JS)
  • sass:讓 Vite 能夠處理 .scss 檔案
  • @popperjs/core:Bootstrap 下拉選單、彈出視窗等元件需要的依賴

設定 main.js 引入方式

方式一:全部引入(簡單快速)

直接在 main.js 中引入所有 Bootstrap CSS 和 JS:

1
2
3
// main.js
import "bootstrap/dist/css/bootstrap.min.css"
import 'bootstrap'

這種方式會把完整的 Bootstrap bundle 引入,適合快速開發或小型專案。

方式二:透過 SCSS 引入(推薦,可自訂變數)

建立 src/scss/main.scss,在 SCSS 中引入 Bootstrap:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// src/scss/main.scss

// 1. 覆蓋 Bootstrap 預設變數(必須在 import bootstrap 之前)
$primary: #6f42c1;       // 自訂主色
$font-size-base: 1rem;
$border-radius: 0.5rem;

// 2. 引入 Bootstrap
@import "bootstrap/scss/bootstrap";

// 3. 加入自訂樣式
body {
  font-family: 'Noto Sans TC', sans-serif;
}

main.js 中引入這個 SCSS 檔案:

1
2
3
// main.js
import './scss/main.scss'
import 'bootstrap'

方式三:部分引入(最小化 Bundle 大小)

只引入需要的 Bootstrap 元件,減少最終 Bundle 大小:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// 必要的功能
@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/mixins";
@import "bootstrap/scss/utilities";

// 只引入需要的元件
@import "bootstrap/scss/reboot";
@import "bootstrap/scss/grid";
@import "bootstrap/scss/buttons";
@import "bootstrap/scss/navbar";
@import "bootstrap/scss/modal";

自訂 Bootstrap 主題色

Bootstrap 5 的所有設計 Token 都可以透過 SCSS 變數覆蓋:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// 覆蓋顏色系統
$primary:    #0d6efd;
$secondary:  #6c757d;
$success:    #198754;
$danger:     #dc3545;
$warning:    #ffc107;
$info:       #0dcaf0;

// 覆蓋間距
$spacer: 1.25rem;

// 覆蓋字型
$font-family-base: 'Noto Sans TC', sans-serif;
$font-size-base: 0.9375rem;

// 覆蓋圓角
$border-radius: 0.375rem;
$border-radius-lg: 0.5rem;

// 必須在這些變數之後才引入 Bootstrap
@import "bootstrap/scss/bootstrap";

引入 Bootstrap Icons

1
npm install bootstrap-icons

在 SCSS 中引入:

1
@import "bootstrap-icons/font/bootstrap-icons.css";

或在 main.js 中引入:

1
import 'bootstrap-icons/font/bootstrap-icons.css'

在 HTML 中使用:

1
2
<i class="bi bi-github"></i>
<i class="bi bi-heart-fill text-danger"></i>

Vite 設定(vite.config.js)

若 SCSS 使用 @import 時出現路徑問題,可在 Vite 設定中加入 additionalData

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  css: {
    preprocessorOptions: {
      scss: {
        // 讓所有 SCSS 檔案都能使用 Bootstrap 的變數和 mixin,不需重複 import
        additionalData: `@import "bootstrap/scss/functions"; @import "bootstrap/scss/variables"; @import "bootstrap/scss/mixins";`
      }
    }
  }
})

參考範例

範例程式碼可參考:cf95a316b4a8fd73621040a135d41cfc304de780