透過 Vite 客製化 Bootstrap:打造你的專屬樣式

Bootstrap 是廣泛應用的前端樣式框架。一般情況下,我們可以直接使用它提供的所有功能。然而,在某些特殊專案中,你可能只需要 Bootstrap 的部分功能,例如,只需要它的自適應網格。那麼,如何根據需求自訂 Bootstrap 呢?

Vite 是一款極速、現代化的前端建構工具。這裡我們以 Vite 為例,客制專屬的 Bootstrap,在進入教學前,請務必確認你已經安裝完 Node.js,安裝完後,請在終端機下輸入:

node -v
npm -v

如果你看到版本號則表示已經安裝成功。

第一步:建立 Vite 專案及資料夾

先開啟終端機,並 cd 到你的預定工作目錄裡,接者在終端機裡輸入下面的指令新增 vite 專案,其中,my-vite-bootstrap-project 可以是你自訂的資料夾名稱。

npm create vite@latest my-vite-bootstrap-project

接著根據終端機的提示 Vanilla 原生 Javascript (如果你熟悉其他前端框架,像是 Vue 或是 React 的話,也可以在這個階段去選取,不一定要選原生的 Vanilla)

緊接者跳到你剛剛新增的專案資料夾

cd my-vite-bootstrap-project

安裝 Vite

npm install

第二步:安裝必要套件

接著安裝 Bootstrap 及 sass

npm install bootstrap sass

第三步:建立 SCSS 與 JS 檔案,並確保資料夾路徑

  • 先在 src 的資料夾下建立 js 及 scss 兩個資料夾
  • 在 js 的資料夾下建立空的 main.js 檔
  • 在 scss 的資料夾下建立空的 style.scss 及 _custom.scss 兩個檔案
src/
├── js/
│ └── main.js
└── scss/
  └── style.scss
  └── _custom.scss

第四步:客製化 Bootstrap,只保留 RWD 網格

Bootstrap 的 SASS 設定檔放在下面的路徑裡

node_modules/
└── bootstrap/
  └── sass

裡面的檔案頗多,如果你要客制化自己的 Bootstrap,不需要全部引用,只需要選擇專案上會用到的即可,以自適應網格為例,style.scss 的設定如下:

@import "bootstrap/scss/functions";

// 自定義的變數,要放在 variables 之前
@import "custom";
@import "bootstrap/scss/variables";

@import "bootstrap/scss/maps";
@import "bootstrap/scss/mixins";
@import "bootstrap/scss/grid";
@import "bootstrap/scss/buttons";
@import "bootstrap/scss/containers";
@import "bootstrap/scss/utilities";
@import "bootstrap/scss/utilities/api";
@import "bootstrap/scss/reboot";

如果你要自訂義 variables,如修改 $primary 的顏色,則可以設定在 _custom.scss 裡面,下面是一個 _custom.scss 的範例,你可以根據自己的需要調整。

$primary: pink;

第五步:在 main.js 匯入 SCSS

開啟 main.js,並加入:

import "/src/scss/style.scss";

第六步:在 index.html 中引入 main.js

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8" />
<title>Vite Bootstrap Grid</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>

<body>
	<div class="container">
		<div class="row">
			<div class="col-6 bg-primary text-white">
				<button class="btn btn-primary">Button</button>
			</div>
			<div class="col-6 bg-secondary text-white">右邊</div>
		</div>
	</div>
	<script type="module" src="/src/js/main.js"></script>
</body>

</html>

預覽

在終端機下輸入下面指令:

npm run dev

在終端機裡看到下面的畫面及表示成功,你可以複製 http://localhost:5173/ 到瀏覽器下預覽。

延伸閱讀

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

返回頂端