ssrCompile.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { ComponentInternalInstance, warn } from 'vue'
  2. import { compile } from '@vue/compiler-ssr'
  3. import { generateCodeFrame, NO } from '@vue/shared'
  4. import { CompilerError } from '@vue/compiler-core'
  5. import { PushFn } from '../render'
  6. type SSRRenderFunction = (
  7. context: any,
  8. push: PushFn,
  9. parentInstance: ComponentInternalInstance
  10. ) => void
  11. const compileCache: Record<string, SSRRenderFunction> = Object.create(null)
  12. export function ssrCompile(
  13. template: string,
  14. instance: ComponentInternalInstance
  15. ): SSRRenderFunction {
  16. const cached = compileCache[template]
  17. if (cached) {
  18. return cached
  19. }
  20. const { code } = compile(template, {
  21. isCustomElement: instance.appContext.config.isCustomElement || NO,
  22. isNativeTag: instance.appContext.config.isNativeTag || NO,
  23. onError(err: CompilerError) {
  24. if (__DEV__) {
  25. const message = `[@vue/server-renderer] Template compilation error: ${
  26. err.message
  27. }`
  28. const codeFrame =
  29. err.loc &&
  30. generateCodeFrame(
  31. template as string,
  32. err.loc.start.offset,
  33. err.loc.end.offset
  34. )
  35. warn(codeFrame ? `${message}\n${codeFrame}` : message)
  36. } else {
  37. throw err
  38. }
  39. }
  40. })
  41. return (compileCache[template] = Function('require', code)(require))
  42. }