locales.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. const path = require('path')
  2. const fs = require('fs-extra')
  3. const globby = require('globby')
  4. const deepmerge = require('deepmerge')
  5. // Subs
  6. const channels = require('../channels')
  7. // Context
  8. const getContext = require('../context')
  9. // Utils
  10. const { log } = require('../util/logger')
  11. let locales
  12. const watchedTrees = new Map()
  13. function list (context) {
  14. return locales
  15. }
  16. function add (locale, context) {
  17. const existing = locales.find(l => l.lang === locale.lang)
  18. if (existing) {
  19. existing.strings = deepmerge(existing.strings, locale.strings)
  20. } else {
  21. locales.push(locale)
  22. }
  23. context.pubsub.publish(channels.LOCALE_ADDED, {
  24. localeAdded: locale
  25. })
  26. }
  27. function reset (context) {
  28. locales = []
  29. // Load builtin locales
  30. const folder = path.resolve(__dirname, '../../')
  31. loadFolder(folder, context)
  32. }
  33. function _loadFolder (root, context) {
  34. const paths = globby.sync(['./locales/*.json'], { cwd: root, absolute: true })
  35. paths.forEach(file => {
  36. const basename = path.basename(file)
  37. const lang = basename.substr(0, basename.indexOf('.'))
  38. const strings = fs.readJsonSync(file)
  39. add({ lang, strings }, context)
  40. })
  41. }
  42. function loadFolder (root, context) {
  43. const folder = path.join(root, './locales')
  44. if (process.env.VUE_APP_CLI_UI_DEV && !watchedTrees.get(root) && fs.existsSync(folder)) {
  45. watchedTrees.set(root, true)
  46. const watch = require('watch')
  47. watch.watchTree(folder, () => {
  48. _loadFolder(root, context)
  49. log('Locales reloaded', root)
  50. })
  51. } else {
  52. _loadFolder(root, context)
  53. }
  54. }
  55. reset(getContext())
  56. module.exports = {
  57. list,
  58. add,
  59. reset,
  60. loadFolder
  61. }