Last active
April 5, 2019 07:58
-
-
Save aadityataparia/2972c69ae5a11bbbbe1f07bd69847a86 to your computer and use it in GitHub Desktop.
Momentjs to Dayjs locale importer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const path = require('path') | |
const momentLocaleFolder = path.join(__dirname, 'locale') | |
const dayjsLocaleFolder = path.join(__dirname, 'src/locale') | |
const saveFolder = path.join(__dirname, 'src/locale') | |
const Moment = require(path.join(__dirname, './moment')) | |
function objectToString(obj, prefix = ' ') { | |
let string = '{' | |
Object.keys(obj).forEach((p, i) => { | |
const str = JSON.stringify(obj[p]) | |
if (str) string += `\n${prefix}${p}: ${str}${i < Object.keys(obj).length - 1 ? ',' : ''}` | |
}) | |
string += '\n},' | |
return string | |
} | |
fs.readdirSync(momentLocaleFolder).forEach((file) => { | |
const filePath = path.join(momentLocaleFolder, file) | |
require(filePath) | |
const momentLocaleRelativeTime = Moment[file.replace('.js', '')].relativeTime | |
const momentLocaleFormats = Moment[file.replace('.js', '')].longDateFormat | |
delete momentLocaleRelativeTime.ss | |
const dayjsFilePath = path.join(dayjsLocaleFolder, file) | |
const dayjsFile = fs.readFileSync(dayjsFilePath, 'utf-8') | |
const oldLocale = dayjsFile.split('const locale = ')[1].split('dayjs.locale')[0] | |
let toBeAdded = '' | |
if (oldLocale.indexOf('formats') < 0) { | |
toBeAdded += `formats: ${objectToString(momentLocaleFormats)}\n ` | |
} | |
if (oldLocale.indexOf('relativeTime') < 0) { | |
toBeAdded += `relativeTime: ${objectToString(momentLocaleRelativeTime)}\n ` | |
} | |
const start = oldLocale.substring(0, oldLocale.lastIndexOf('}')) | |
const end = oldLocale.substring(oldLocale.lastIndexOf('}'), oldLocale.length) | |
const localeToWrite = `${start}${toBeAdded ? ',' : ''}${toBeAdded}${end}` | |
const saveLocalePath = path.join(saveFolder, file) | |
fs.writeFileSync(saveLocalePath, `import dayjs from 'dayjs' | |
const locale = ${localeToWrite}dayjs.locale(locale, null, true) | |
export default locale | |
`) | |
}) | |
// Copy momentjs locales folder to `locale` folder in dayjs root | |
// Create dummy `moment.js` with contents | |
// module.exports = { | |
// defineLocale(name, val) { | |
// this[name] = val | |
// } | |
// } | |
// Change `saveFolder` if you want to test before overwriting original files in dayjs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment