template-compiler.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. var chalk = require('chalk')
  2. var vueCompiler = require('vue-template-compiler')
  3. var transpile = require('vue-template-es2015-compiler')
  4. var compilePug = require('./compilers/pug-compiler')
  5. var compileJade = require('./compilers/jade-compiler')
  6. var compileHaml = require('./compilers/haml-compiler')
  7. const throwError = require('./throw-error')
  8. function getTemplateContent (templatePart, config) {
  9. if (templatePart.lang === 'pug') {
  10. return compilePug(templatePart, config)
  11. }
  12. if (templatePart.lang === 'jade') {
  13. return compileJade(templatePart.content)
  14. }
  15. if (templatePart.lang === 'haml') {
  16. return compileHaml(templatePart.content)
  17. }
  18. return templatePart.content
  19. }
  20. module.exports = function compileTemplate (templatePart, config) {
  21. var templateContent = getTemplateContent(templatePart, config)
  22. var compiled = vueCompiler.compile(templateContent)
  23. if (compiled.errors.length) {
  24. compiled.errors.forEach(function (msg) {
  25. console.error('\n' + chalk.red(msg) + '\n')
  26. })
  27. throwError('Vue template compilation failed')
  28. } else {
  29. return compile(compiled, templatePart.attrs.functional)
  30. }
  31. }
  32. function compile (compiled, isFunctional) {
  33. function toFunction (code) {
  34. var renderArgs = isFunctional ? '_h, _vm' : ''
  35. return transpile('function render (' + renderArgs + ') {' + code + '}', {
  36. transforms: { stripWithFunctional: isFunctional }
  37. })
  38. }
  39. return {
  40. render: toFunction(compiled.render),
  41. staticRenderFns: '[' + compiled.staticRenderFns.map(toFunction).join(',') + ']'
  42. }
  43. }