本地项目一键开启 HTTPS(mkcert + Vite / Vue 配置教程)

455 阅读1分钟

在本地开发中,有些第三方登录(比如 微信登录 / TikTok 登录)会要求必须是 https 环境。
那我们本地调试时,怎么快速给项目加上 HTTPS 呢?

今天分享一个超好用的小工具 —— mkcert,结合 Vite / Vue 配置,让本地项目一秒切换到 HTTPS!

mkcert.exe

需要科学上网:https://github.com/FiloSottile/mkcert/releases

下载后改名为mkcert.exe将该exe文件放到项目根目录中

cmd

项目根目录打开cmd运行指令

mkcert.exe -install

提示 The local CA is already installed in the system trust store! 👍 接着下个命令

mkcert.exe localhost

这会生成文件,不需要关注

vite.config配置

项目根目录如果不存在 vite.config.js 则创建该文件,加入以下内容

import {
	defineConfig
} from 'vite'
import fs from 'fs'
import path from 'path'
import uni from '@dcloudio/vite-plugin-uni';

// https://vite.dev/config/
export default defineConfig({
	plugins: [uni()],
	server: {
		https: {
			key: fs.readFileSync(path.resolve(__dirname, 'localhost-key.pem')),
			cert: fs.readFileSync(path.resolve(__dirname, 'localhost.pem')),
		},
		port: 5177,
	},
})

其中用到一些包,根据提示安装一下

重启服务观察是否已经是https

vue.config配置

const fs = require('fs')
const path = require('path')

module.exports = {
  devServer: {
    https: {
      key: fs.readFileSync(path.resolve(__dirname, 'localhost-key.pem')),
      cert: fs.readFileSync(path.resolve(__dirname, 'localhost.pem')),
    },
    port: 8080, // 自己改端口
    host: '0.0.0.0'
  }
}