index.ts 1.4 KB

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