index.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { createLogger, type PluginOption } from 'vite'
  2. import { PLUGIN_NAME } from './lib/constant'
  3. import { getDefaultHosts } from './lib/util'
  4. import Mkcert, { type MkcertBaseOptions } from './mkcert/index'
  5. export { BaseSource, type SourceInfo } from './mkcert/source'
  6. export type MkcertPluginOptions = MkcertBaseOptions & {
  7. /**
  8. * The hosts that needs to generate the certificate.
  9. */
  10. hosts?: string[]
  11. }
  12. const plugin = (options: MkcertPluginOptions = {}): PluginOption => {
  13. return {
  14. name: PLUGIN_NAME,
  15. apply: 'serve',
  16. config: async ({ server = {}, logLevel }) => {
  17. // v5.0 以下支持 boolean 类型的 https 配置
  18. if (typeof server.https === 'boolean' && server.https === false) {
  19. return
  20. }
  21. const { hosts = [], ...mkcertOptions } = options
  22. const logger = createLogger(logLevel, {
  23. prefix: PLUGIN_NAME
  24. })
  25. const mkcert = Mkcert.create({
  26. logger,
  27. ...mkcertOptions
  28. })
  29. await mkcert.init()
  30. const allHosts = [...getDefaultHosts(), ...hosts]
  31. if (typeof server.host === 'string') {
  32. allHosts.push(server.host)
  33. }
  34. const uniqueHosts = Array.from(new Set(allHosts)).filter(Boolean)
  35. const certificate = await mkcert.install(uniqueHosts)
  36. const httpsConfig = {
  37. key: certificate.key && Buffer.from(certificate.key),
  38. cert: certificate.cert && Buffer.from(certificate.cert)
  39. }
  40. return {
  41. server: {
  42. https: httpsConfig
  43. },
  44. preview: {
  45. https: httpsConfig
  46. }
  47. }
  48. }
  49. }
  50. }
  51. export default plugin