var fs = require('fs'); var path = require('path'); var params = {}; TranslationPlugin.loader = function(options) { let path = options.path ? options.path : "none"; return require.resolve("./loader") + "?path="+path; }; function TranslationPlugin(options) { // Setup the plugin instance with options... params = options; } requireContext = function(base, scan_subdirectories, regular_expression) { const contents = {}; function read_directory(directory) { for (let child of fs.readdirSync(directory)) { const full_path = path.join(directory, child); if (fs.statSync(full_path).isDirectory()) { if (scan_subdirectories) { read_directory(full_path); } } else { if (regular_expression && !full_path.match(regular_expression)) { continue; } contents[path.relative(base, full_path)] = require(full_path); delete require.cache[require.resolve(full_path)] } } } read_directory(base); return contents; } function compare(first, second) { let secondKeys= Object.keys(second); let firstKeys = Object.keys(first); for(let key of firstKeys) { if ( secondKeys.indexOf(key) === -1 || second[key].localeCompare(first[key])) { return false; } } for(let key of secondKeys) { if ( firstKeys.indexOf(key) === -1 || first[key].localeCompare(second[key])) { return false; } } return true; } TranslationPlugin.prototype.apply = function(compiler) { compiler.plugin('done', function() { try { let translations = {}; let chunks = requireContext(params.path, false, /\.json$/); Object.keys(chunks).forEach(function(chunk, index) { translations = Object.assign({}, translations, chunks[chunk]); }); let data = {}; const path = params.output+"/"+params.lang+".json"; let write = true; let old = {}; try { old = require(path)[params.lang]; delete require.cache[require.resolve(path)]; } catch (Exception) { console.log("Can't load file"); } write = !compare(translations, old); data[params.lang] = translations; if (write) { try { fs.unlinkSync(path); } catch(err) { } fs.writeFile(path, JSON.stringify(data), function(err) { if(err) { return console.log(err); } }); } } catch (Exception) { console.error(Exception); } }); }; module.exports = TranslationPlugin;