在vite中使用mkcert创建https

207 阅读1分钟

开发过程中会遇到一些需要使用https的场景,如获取定位,需要https,或者localhost,浏览器桌面级的通知都需要https的安全限制

其他方式有,我懒得去整理了,现在就使用mkcert实现

[mkcert](FiloSottile/mkcert: A simple zero-config tool to make locally trusted development certificates with any names you'd like. (github.com))

安装

image.png

choco install mkcert

我使用的windows11,为什么不使用安装包?因为遇到问题

生成证书

mkcert localhost 127.0.0.1 ::1 192.168.5.240

这里我建议在打开的文件夹中使用cmd或者poershell

image.png

再运行命令 mkcert localhost 127.0.0.1 ::1 192.168.5.240

image.png 这样就会直接生成到当前文件夹中

vite中使用

import vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import path, { resolve } from 'path'
import { readFileSync } from 'fs'

export default defineConfig({
  plugins: [
    vue({
      template: {
        compilerOptions: {
          isCustomElement: tag => ['font', 'center'].includes(tag)
        }
      }
    }),
    AutoImport({
      resolvers: [ElementPlusResolver()]
    }),
    Components({
      resolvers: [ElementPlusResolver()]
    })
  ],
  resolve: {
    // 设置文件目录别名
    alias: {
      '@': resolve(__dirname, './src')
    },
    extensions: ['.js', '.ts', '.tsx', '.jsx']
  },
  server: {
    host: true,
    https: {
      key: readFileSync(path.join(__dirname, './cert/localhost+3-key.pem')),
      cert: readFileSync(path.join(__dirname, './cert/localhost+3.pem')),
    }
  }
})


image.png

OJBK!