Skip to content

Instantly share code, notes, and snippets.

@benkeen
Created April 28, 2020 01:17
Show Gist options
  • Save benkeen/244e6c563a10022182ed0541d3a722e0 to your computer and use it in GitHub Desktop.
Save benkeen/244e6c563a10022182ed0541d3a722e0 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const ORIGINAL_LOCALE_FOLDER = './src/locale';
const NEW_DATA_FOLDER = './src/data';
// our new data folder
if (!fs.existsSync(NEW_DATA_FOLDER)){
fs.mkdirSync(NEW_DATA_FOLDER);
}
const getLocaleFiles = () => {
const map = {};
fs.readdirSync(ORIGINAL_LOCALE_FOLDER).forEach((filename) => {
const [locale, ] = filename.split('.');
const content = fs.readFileSync(`${ORIGINAL_LOCALE_FOLDER}/${filename}`, 'utf8');
map[locale] = content.trim();
});
return map;
};
const getEs6ModuleContent = (localeFiles) => {
const newFileMap = {};
Object.keys(localeFiles).forEach((locale) => {
let content = localeFiles[locale].replace(/import moment from '..\/moment';\n\n?/, '');
content = content.replace(/export default moment\.defineLocale\('[a-zA-Z\-']+', \{/, 'export default {');
content = content.replace(/\}\)\;$/, '};\n');
newFileMap[locale] = content;
});
return newFileMap;
};
const createNewLocaleModules = (localeFiles) => {
const content = getEs6ModuleContent(localeFiles);
Object.keys(content).forEach((locale) => {
fs.writeFileSync(`${NEW_DATA_FOLDER}/${locale}.js`, content[locale]);
});
};
const getNewContent = (locale) => `import moment from '../moment';
import data from '../data/${locale}';
export default moment.defineLocale('${locale}', data);
`;
const updateOldLocaleFiles = (localeFiles) => {
Object.keys(localeFiles).forEach((locale) => {
const content = getNewContent(locale);
fs.unlinkSync(`${ORIGINAL_LOCALE_FOLDER}/${locale}.js`);
fs.writeFileSync(`${ORIGINAL_LOCALE_FOLDER}/${locale}.js`, content);
});
};
const localeFiles = getLocaleFiles();
createNewLocaleModules(localeFiles);
updateOldLocaleFiles(localeFiles);
@rodion1221
Copy link

G

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment