index.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. var fs = require('fs');
  2. var path = require('path');
  3. var params = {};
  4. TranslationPlugin.loader = function(options) {
  5. let path = options.path ? options.path : "none";
  6. return require.resolve("./loader") + "?path="+path;
  7. };
  8. function TranslationPlugin(options) {
  9. // Setup the plugin instance with options...
  10. params = options;
  11. }
  12. requireContext = function(base, scan_subdirectories, regular_expression) {
  13. const contents = {};
  14. function read_directory(directory) {
  15. for (let child of fs.readdirSync(directory)) {
  16. const full_path = path.join(directory, child);
  17. if (fs.statSync(full_path).isDirectory()) {
  18. if (scan_subdirectories) {
  19. read_directory(full_path);
  20. }
  21. } else {
  22. if (regular_expression && !full_path.match(regular_expression)) {
  23. continue;
  24. }
  25. contents[path.relative(base, full_path)] = require(full_path);
  26. delete require.cache[require.resolve(full_path)]
  27. }
  28. }
  29. }
  30. read_directory(base);
  31. return contents;
  32. }
  33. function compare(first, second) {
  34. let secondKeys= Object.keys(second);
  35. let firstKeys = Object.keys(first);
  36. for(let key of firstKeys) {
  37. if ( secondKeys.indexOf(key) === -1 || second[key].localeCompare(first[key])) {
  38. return false;
  39. }
  40. }
  41. for(let key of secondKeys) {
  42. if ( firstKeys.indexOf(key) === -1 || first[key].localeCompare(second[key])) {
  43. return false;
  44. }
  45. }
  46. return true;
  47. }
  48. TranslationPlugin.prototype.apply = function(compiler) {
  49. compiler.plugin('done', function() {
  50. try {
  51. let translations = {};
  52. let chunks = requireContext(params.path, false, /\.json$/);
  53. Object.keys(chunks).forEach(function(chunk, index) {
  54. translations = Object.assign({}, translations, chunks[chunk]);
  55. });
  56. let data = {};
  57. const path = params.output+"/"+params.lang+".json";
  58. let write = true;
  59. let old = {};
  60. try {
  61. old = require(path)[params.lang];
  62. delete require.cache[require.resolve(path)];
  63. } catch (Exception) {
  64. console.log("Can't load file");
  65. }
  66. write = !compare(translations, old);
  67. data[params.lang] = translations;
  68. if (write) {
  69. try {
  70. fs.unlinkSync(path);
  71. } catch(err) {
  72. }
  73. fs.writeFile(path, JSON.stringify(data), function(err) {
  74. if(err) {
  75. return console.log(err);
  76. }
  77. });
  78. }
  79. } catch (Exception) {
  80. console.error(Exception);
  81. }
  82. });
  83. };
  84. module.exports = TranslationPlugin;