index.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // This package is the "full-build" that includes both the runtime
  2. // and the compiler, and supports on-the-fly compilation of the template option.
  3. import { compile, CompilerOptions, CompilerError } from '@vue/compiler-dom'
  4. import { registerRuntimeCompiler, RenderFunction, warn } from '@vue/runtime-dom'
  5. import * as runtimeDom from '@vue/runtime-dom'
  6. import { isString, NOOP, generateCodeFrame } from '@vue/shared'
  7. const compileCache: Record<string, RenderFunction> = Object.create(null)
  8. function compileToFunction(
  9. template: string | HTMLElement,
  10. options?: CompilerOptions
  11. ): RenderFunction {
  12. if (!isString(template)) {
  13. if (template.nodeType) {
  14. template = template.innerHTML
  15. } else {
  16. __DEV__ && warn(`invalid template option: `, template)
  17. return NOOP
  18. }
  19. }
  20. const key = template
  21. const cached = compileCache[key]
  22. if (cached) {
  23. return cached
  24. }
  25. if (template[0] === '#') {
  26. const el = document.querySelector(template)
  27. if (__DEV__ && !el) {
  28. warn(`Template element not found or is empty: ${template}`)
  29. }
  30. template = el ? el.innerHTML : ``
  31. }
  32. const { code } = compile(template, {
  33. hoistStatic: true,
  34. cacheHandlers: true,
  35. onError(err: CompilerError) {
  36. if (__DEV__) {
  37. const message = `Template compilation error: ${err.message}`
  38. const codeFrame =
  39. err.loc &&
  40. generateCodeFrame(
  41. template as string,
  42. err.loc.start.offset,
  43. err.loc.end.offset
  44. )
  45. warn(codeFrame ? `${message}\n${codeFrame}` : message)
  46. }
  47. },
  48. ...options
  49. })
  50. const render = new Function('Vue', code)(runtimeDom) as RenderFunction
  51. return (compileCache[key] = render)
  52. }
  53. registerRuntimeCompiler(compileToFunction)
  54. export { compileToFunction as compile }
  55. export * from '@vue/runtime-dom'
  56. if (__BROWSER__ && __DEV__) {
  57. console[console.info ? 'info' : 'log'](
  58. `You are running a development build of Vue.\n` +
  59. `Make sure to use the production build (*.prod.js) when deploying for production.`
  60. )
  61. }