Vite+Sass in VanillaJS 編譯環境建構教學筆記
===
綱要:
[TOC]
本課程完整範例
---
原始碼請參閱:https://github.com/fortes1219/vite_vanilla
## 安裝nvm
安裝NodeJS以前先安裝nvm的nodeJS版本管理包,以後如果我們要切換成其他的NodeJS版本會方便得多。
### Windows
選擇`nvm-setup.zip`下來安裝
https://github.com/coreybutler/nvm-windows/releases
一路跟著安裝指示結束安裝後,到終端機輸入`nvm`
如果有看到這個畫面代表OK了:

### Mac OSX
使用bash指令安裝nvm
`curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh`
安裝後同樣可以打開終端機,輸入`nvm`看是否成功出現nvm相關指令
## 安裝NodeJS

https://nodejs.org/en/
==安裝標示LTS的穩定版本==,因為我們需要設定Windows的環境變數,這邊只要是挑18.0以上的版本即可。可以從官方這個按鈕下載安裝黨,但==比較推薦安裝完NVM以後直接使用它來安裝==
---
### 如何安裝與切換其他版本的NodeJS (Win/OSX通用指令)
:::info
如果日後想要安裝其他比現行LTS更低的版本
只要在終端機輸入這些指令就可以安裝與切換
:::
**安裝**
`nvm install 16.14.0`
**切換版本**
`nvm use 16.14.0`
---
### Windows 10/11
安裝好後接下來打開windows的「設定」

然後搜尋**系統環境變數**

按下**環境變數** >> 在下面的**系統變數**中找出**Path** >> 按一下**編輯**

檢查你的NodeJS是否有確實的存在Path當中,然後打開**命令提示字元**

或者在畫面下方工具列的win圖示上右鍵 >> 執行 >> 輸入**cmd**來開啟

命令列輸入`npm`,如果有出現這些畫面訊息代表安裝成功
### Windows PowerShell 權限問題排除
:::info
若敲指令時發生「npm 不是内部或外部命令」的錯誤訊息出現時。
我們需要調整一下Windows的PowerShell權限設定。
:::
在開始選單下的「Windows PowerShell」下,以系統管理員身分執行一次

並且輸入指令:`Set-ExecutionPolicy RemoteSigned`

輸入A選擇「全部皆是」,然後把終端機重開即可。

:::info
如果你真的很懶的處理windows的問題,直接使用git附帶的bash也行
:::
---
### Mac OSX
假如你用的電腦是MAC OSX環境,而從來沒有取得過寫入系統的管理權限,務必參考以下的做法。因為我們在安裝任何需要global全域形式的NodeJS套件都會動用到系統環境資源。

假如沒有設定系統權限,`npm install -g` 的指令就會像這樣顯示失敗
我們可以先用權限檢查指令 `ls -l /usr/local` 來查看目前電腦使用者是否擁有寫入權限:

OSX使用的是Linux指令,最左側的訊息表示:
```
d : 目錄 (dir)
r : 讀取權 (read)
w : 寫入權 (write)
x : 執行權 (execute)
```
現在我們可以用這個指令來改寫權限,讓藏在/usr/local/中的node_modules擁有寫入權限:
`sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}`
==注意,sudo指令會需要輸入這台電腦的登入密碼,密碼鍵入時不會顯示任何內容,不是當機喔==
---
安裝VSCODE和語法輔助工具
===

網址:https://code.visualstudio.com/
安裝成功後打開VSCODE,按一下左下的**Extensions**開啟擴充套件視窗,搜尋以下幾個套件:
**1. Path intellisense**

輔助尋找檔案路徑的工具
**2. HTML 5 Snippets**

包含所有 HTML 5 的 TAG 語法提示輔助工具
**3. HTML CSS Support**

HTML 5 和 CSS 的寫作輔助
**4. Sass**

Sass的編譯輔助工具,檢查語法、格式化排版等
---
安裝Vite並且建立一個基礎模板
===

官方文件:https://cn.vitejs.dev/guide/
Vite的最低 nodeJS 版本需要 12.0.0 以上,剛才我們安裝的版本是比較新的。
我們在D槽,或者任何你想放置專案的路徑下新增一個目錄,命名為 `course`
然後打開終端機(WIN裡叫做命令提示字元,統稱cmd或終端機)進入這個 course 目錄
並且輸入:
```bash=
npm create vite@latest
```

接著Vite安裝套件會問你要取什麼名字,我們輸入`vite_vanilla`
然後對著 Vanilla 按下 Enter (Mac 是按 return),variant 一樣繼續選 Vanilla


接著會看到這個安裝完成訊息
然後會要我們依照它的指示進入這個目錄安裝node module後啟動環境

先安裝 node modules
```bash=
npm install
```

接著不繼續在終端機進行啟環境的動作,我們要改在VSCODE的終端機功能下進行
我們要配置一個`.gitignore`檔案到專案根目錄裡面。
避免git會將node_modules的內容也一併列入變更:

```BASH
# .gitignore
# commonly ignored file patterns.
node_modules/
dist/
```
這邊先放著不管,下一步是將這個專案丟上Git倉庫做版控,如果你不想在這階段進版控可以跳過。
---
將專案放上Git做版控
---

安裝好 node modules 後就可以將專案推到你慣用的Git倉庫,如Github、Gitee、GitLab等
如果你沒學過Git,或者想從舊時代的SVN轉跳來學Git,可以參考這份教學筆記:
[Git with SmartGit 版本控制教學](https://hackmd.io/@FortesHuang/H1wlrMp79)
故以下我們省略Git的安裝和部分操作等細節,著重在完成專案的遠端連結
首先在Github上開一個新的專案,跟剛才建立的 Vite 專案一樣命名為 **vite_vanilla**

記得複製一下Github上,你的專案位置

然後用你慣用的Git圖形化管理程式新增剛才在 ==**本地端**== 建好的專案,這裡用SmartGit為例:


回到CMD,依序輸入以下指令來初始化 Git 和新增 Remote 並且 push 上去
```bash=
git init
git remote add origin https://github.com/fortes1219/vite_vanilla.git
git add .
git commit -m "Initial commit"
git push -u origin master
```

確認你的專案有和Remote建立好即可。
---
進入 VSCODE 配置網頁檔案與 Vite 設定檔
---

打開專案所在的路徑,並且新增一個叫做 **vite.config.js** 的檔案

然後新增我們常用的檔案目錄、以及兩個網頁檔,分別是 **topic.html**、**contact.html**
你可以視情況加點內容上去,但一定要注意一件很重要的事情:
==**不要更動main.js的位置,也不要移除每個頁面中將它引入的程式碼**==

接著我們新增一個目錄 **src**,在裡面新增 **styles**、以及 **img** 兩個目錄,隨便找張圖丟進 **img**
==並記得把原本存在根目錄下的 **style.css** 刪除==
然後新增 **style.scss** 這隻檔案到 **styles**,加些基本樣式:

因為無論是在存檔時或打包時都需要編譯 Sass/Scss ,現在我們需要它的編譯套件。

打開VSCODE上的終端機,依序輸入安裝套件的指令:
```bash=
npm add -D sass
npm add -D sass-loader
```

安裝好後,開啟 **main.js** ,將 **style.scss** 引入

接著來設定 **vite.config.js**
由於沒技術背景的萌新們大多不會寫 javascript ,自然不會知道基本設定要怎麼做
這裡提供一個基本範例,每段程式碼的用途可以看註解:
[原檔(Github)](https://github.com/fortes1219/vite_vanilla/blob/master/vite.config.js)
```javascript=
// vite.config.js
import { defineConfig } from "vite";
import path, { resolve } from "path";
export default defineConfig({
// 指定預設的根目錄
base: "./",
// 判別現在是開發環境或打包後部署上去的遠端環境,遠端名稱要跟你的Github專案一樣
publicPath: process.env.NODE_ENV === "production" ? "/vite_vanilla/" : "./",
resolve: {
// 寫js相關模組時對應路徑的別名,增加引用的便利性
alias: {
"@": path.resolve(__dirname, "src"),
"assets": path.resolve(__dirname, "src/assets/"),
"img": path.resolve(__dirname, "src/img"),
"styles": path.resolve(__dirname, "src/styles/"),
"pages": path.resolve(__dirname, "src/pages/"),
},
},
build: {
// 這裡用的是底層相依套件Rollup,設定入口頁面和打包出來的各個資源目錄要長什麼樣子
// 和Vue、React等不同,這份教學展示的是靜態網頁,所以可以設定多個入口HTML檔彼此連結
rollupOptions: {
input: {
// 首頁須使用main作為命名,指向index.html,其他依照檔名即可
main: resolve(__dirname, "index.html"),
topic: resolve(__dirname, "topic.html"),
contact: resolve(__dirname, "contact.html"),
},
output: {
/*
[name]是對應的檔名,hash則是打包後會加上類似亂碼的字元
用以防止檔案被Server端Cache住,造成畫面看起來沒更新
*/
chunkFileNames: "js/[name].[hash].js",
entryFileNames: "js/[name].[hash].js",
/*
對應的副檔名在打包後會自動幫你歸類到所屬的目錄下
*/
assetFileNames: (info) => {
let type = info.name.split(".")[1];
if (/png|jpe?g|svg|gif|tiff|bmp|ico|webp/i.test(type)) {
type = "img";
} else if (/ttf|eot|woff|woff2/i.test(type)) {
type = "fonts"
} else if (/mp4|webm|ogg/i.test(type)) {
type = "video"
} else if (/mp3|wav/i.test(type)) {
type = "sound"
}
return `${type}/[name]-[hash].[ext]`;
},
},
},
cssCodeSplit: false,
},
cssPreprocessOptions: {
// 如果要使用SASS全域變數就在這裡設定路徑
scss: {
// additionalData: '@import "./styles/variable.scss";',
},
},
css: {
// 官方列為實驗性功能,可以找出是由哪個來源建構的css
devSourceMap: true,
},
});
```
設定好 config 後,可以試著在VSCODE終端機啟動環境預覽頁面:
```bash=
npm run dev
```

開啟瀏覽器進入圖示網址 `http://localhost:3000/` 會看到你在index.html設計的畫面

確認一下超連結是否都正常啟用

假如都沒問題,我們就可以進行打包作業,隨便開個CMD指向這個專案目錄後,輸入:
```bash=
npm run build
```
可以看到生成了一個**dist**目錄,相應的副檔名也都有分類到正確的目錄下

---
部署到Github
---
我們回到VSCODE,專案根目錄下新增一個 **==deploy.sh==**

按照以下設定內容,記得將Git專案連結替換成你自己的位置:
```bash=
#!/usr/bin/env sh
# 當發生錯誤時終止腳本運行
set -e
# 打包
npm run build
# 移動至到打包後的dist目錄
cd dist
# 因為dist資料夾預設是被ignore的,在進入dist資料夾後初始化git
git init
git add -A
git commit -m 'deploy'
# 部署到 https://github.com/fortes1219/vite_vanilla.git 分支為 gh-pages
git push -f https://github.com/fortes1219/vite_vanilla.git master:gh-pages
# 將dist資料夾中的內容推送至遠端的gh-pages分支中,並強制將舊有的內容取代成目前的內容(指令 git push -f)
cd -
```
打開CMD,指向專案後輸入下面的指令啟動這個檔案
```bash=
sh ./deploy.sh
```

接著可以打開Github的專案頁面,按下Settings

選單這裡有個Page,進入這個畫面會看到你的個人網頁位置:

順便開啟開發人員工具,可以看見引入的檔案全都依照vite打包設定的檔名格式引用

而你在本地端的dist目錄下的css、js等檔案中可以發現,全都被壓縮處理過,達到最小體積

最後別忘了Git Commit,並push到Remote專案上

---
###### tags: `vite` `vanilla` `sass`