2025年11月4日 星期二

筆記 前端開發簡易使用https方法 VS Code + mkcert + Vite

情境如果已經拿到一個網站是"資料夾類型"例如剛切好html + css + javascript,測試時想使用https開啟瀏覽器,Live Server雖然也可以,但是比較麻煩複雜,又不一定成功,以下方式AI提供測試改良,蠻簡單的。
PS.已經是vite專案的話1>5>6即可
1.下載mkcert,一般windows選mkcert-v1.4.4-windows-amd64.exe,下載後重新命名"mkcert.exe",放於C:\Windows或C:\Windows\System32底下
2.新增vite.config.js package.json .gitignore到專案底下,內容如下
vite.config.js

import { defineConfig } from 'vite';
import fs from 'fs';

export default defineConfig({
  server: {
    https: {
      key: fs.readFileSync('./localhost-key.pem'),
      cert: fs.readFileSync('./localhost.pem')
    },
    port: 3000,
    open: true
  }
});
package.json

{
  "name": "yourname",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview"
  },
  "devDependencies": {
    "vite": "^7.1.12"
  }
}
.gitignore

node_modules/
dist/
.vite/
npm-debug.log*
.yarn-debug.log*
.yarn-error.log*
.pnpm-debug.log*
.vscode/
.DS_Store
Thumbs.db

# mkcert local certificates
localhost.pem
localhost-key.pem
3.改package.json裡的name變成你的專案名稱
4.termainal > npm install -y
5.termainal > mkcert localhost(產生憑證)
6.termainal > npm run dev