get-i18n-block.js 738 B

1234567891011121314151617181920212223242526272829303132
  1. const reg = /<i18n[^>]*>([\s\S]*?)<\/i18n>/
  2. const fs = require('fs')
  3. const yamlReader = require('js-yaml')
  4. // @todo add global cache
  5. // @todo try parse
  6. function get (code, isFile = false) {
  7. let content = code
  8. if (isFile) {
  9. content = fs.readFileSync(code, 'utf-8')
  10. }
  11. const results = content.match(/<i18n[^>]*>([\s\S]*?)<\/i18n>/)
  12. try {
  13. const local = yamlReader.safeLoad(results[1])
  14. return local
  15. } catch (e) {
  16. return {}
  17. }
  18. }
  19. function getWithLocale ({ code = '', isFile = false, locale = ''}) {
  20. const rs = get(code, isFile)
  21. let _rs = {}
  22. for (let i in rs) {
  23. _rs[i] = typeof rs[i][locale] === 'undefined' ? i : rs[i][locale]
  24. }
  25. return _rs
  26. }
  27. exports.get = get
  28. exports.getWithLocale = getWithLocale