i18n-unused.js
1 var fs = require('fs'); 2 var glob = require('glob'); 3 4 glob( 5 '**/*.{js,jsx,ts,tsx}', 6 {ignore: ['**/node_modules/**'], absolute: true}, 7 function (err, filesPaths) { 8 if (err) { 9 console.log(err); 10 return; 11 } 12 13 const i18nSourceFileRelativePath = '/locales/en.json'; 14 const i18nSourceFilePath = `${__dirname}${i18nSourceFileRelativePath}`; 15 16 const sourceJson = fs.readFileSync(i18nSourceFilePath, 'UTF-8'); 17 const preSourceTranslations = JSON.parse(sourceJson); 18 const preKeys = Object.keys(preSourceTranslations); 19 20 const keysToKeep = preKeys.filter(k => k.split('.')[0] === 'PROTECTED'); 21 filesPaths.forEach(filePath => { 22 const content = fs.readFileSync(filePath, 'UTF-8'); 23 24 preKeys.forEach(key => { 25 if (content.includes(key) && !keysToKeep.includes(key)) { 26 keysToKeep.push(key); 27 28 //supports plurals for english source translation 29 if (preKeys.includes(`${key}_plural`)) { 30 keysToKeep.push(`${key}_plural`); 31 } 32 } 33 }); 34 }); 35 36 const sourceTranslationsToKeep = {}; 37 keysToKeep.sort(); 38 keysToKeep.forEach(key => { 39 sourceTranslationsToKeep[key] = preSourceTranslations[key]; 40 }); 41 42 const sourceJsonToKeep = JSON.stringify(sourceTranslationsToKeep, null, 4); 43 fs.writeFileSync(i18nSourceFilePath, sourceJsonToKeep); 44 console.warn( 45 `This script is a workaround, ${ 46 preKeys.length - keysToKeep.length 47 } keys were removed from the ${i18nSourceFileRelativePath}, please make sure to review them before running i18n-format and adapt the code to avoid future deletion.` 48 ); 49 } 50 );