template-compiler.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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) {
  9. if (templatePart.lang === 'pug') {
  10. return compilePug(templatePart.content)
  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) {
  21. var templateContent = getTemplateContent(templatePart)
  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 {
  30. render: toFunction(compiled.render),
  31. staticRenderFns: '[' + compiled.staticRenderFns.map(toFunction).join(',') + ']'
  32. }
  33. }
  34. }
  35. function toFunction (code) {
  36. return transpile('function render () {' + code + '}')
  37. }