Skip to content
文章目录

什么时候需要使用 https

  • 后台接口使用的是 https(http 网站不能请求 https 的接口)
  • 当本地使用 http 进行开发时,发现 vite 对于大量请求处理速度特别慢时(不一定可以解决问题,但可以尝试,毕竟 http 是有请求并发限制的(是 http1.1),https 理论上没有并发限制的是(http2.0))

配置方式

pnpm add vite-plugin-mkcert -D

这个插件是用于生成 https 的证书,并让 chrome 信任该证书

js
import { defineConfig, loadEnv, PluginOption, UserConfigExport } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { resolve } from 'node:path'
import mkcert from 'vite-plugin-mkcert'
import { Agent as HttpAgent } from 'https'

function _resolve(dir: string) {
  return resolve(__dirname, dir)
}

export default defineConfig(({ command, mode }) => {
  const root = process.cwd()
  // 读取.env中配置的环境变量
  const env = loadEnv(mode, root)
  console.log('执行命令: ', command, ', mode:', mode, ', env配置文件数据: ', env)

  // 其他可选插件
  const otherPlugins: PluginOption[] = []
  if (command === 'serve' || mode === 'development') {
    otherPlugins.push(
      mkcert({
        // hosts 默认是你 localhost 以及你的本地 ip。如果有问题,可以自己手动设置
        hosts: ['localhost', '192.168.31.200'],
        // 国内用户从coding下载证书
        source: 'coding',
        // 是否每次都重新生成证书. 默认是false
        force: true,
      })
    )
  }
  const resultConfig: UserConfigExport = {
    plugins: [vue(), vueJsx(), ...otherPlugins],
    server: {
      host: '0.0.0.0',
      // 如果启用有问题,可以尝试将端口改为443,毕竟https的默认端口就是443
      port: 4200,
      open: true,
      // 启用https
      https: true,
      proxy: {
        '/online-mock-api': {
          target: env.VITE_PROXY_TARGET,
          changeOrigin: true,
          agent: new HttpAgent({ keepAlive: true, keepAliveMsecs: 20000 }),
          rewrite: path => {
            const ret = path.replace(/^\/online-mock-api/, '/api')
            return ret
          },
        },
      },
    },
  }

  return resultConfig
})

额外的补充

本地开发时,尽量关闭浏览器的广告过滤插件,或者会拦截请求的插件,对提高资源加载速度,也有一定帮助

参考资料

[vite] http proxy error #8998

vite-plugin-mkcert

Vite 解决项目刷新慢问题(请求量过大)