Last active
April 15, 2019 07:42
-
-
Save toadkicker/99551a94d0922e43a18aea7c6169a62e to your computer and use it in GitHub Desktop.
Convert Rails i18n YAML fies to JSON using Node. Built for vue-i18n to read json files from `config/locales/` in a Nuxt.js project.
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
module.exports = { | |
locales: [ | |
{ | |
code: 'en', | |
iso: 'en-US', | |
name: 'English', | |
file: 'en.json' | |
} | |
] | |
} |
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 yaml = require('js-yaml'); | |
const fs = require('fs'); | |
const localesConfig = require('./index'); | |
// Read the Rails i18n en.yml file, write it to json in the locales directory. | |
// This is because we want a copy of the values to ship with the UI but only | |
// require the need to store them in one location. UI Components can still override | |
// these values when providing their own configuration. | |
module.exports = { | |
writeLocaleJsonFromRailsYaml: function (langCode = 'en') { | |
try { | |
let yml = yaml.safeLoad(fs.readFileSync(`../config/locales/${langCode}.yml`, 'utf8')); | |
fs.writeFileSync(`config/locales/${langCode}.json`, JSON.stringify(yml[langCode]), 'utf8', (err) => { | |
if (err) throw err; | |
console.log(`${langCode}.json has been saved to config/locales`); | |
}); | |
} catch (e) { | |
console.log(e); | |
} | |
}, | |
readLocaleJson: function (langCode) { | |
return JSON.parse(fs.readFileSync(`config/locales/${langCode}.json`, 'utf8')); | |
}, | |
build: function () { | |
if (process.env.NODE_ENV === 'development') { | |
localesConfig.locales.forEach((locale) => { | |
this.writeLocaleJsonFromRailsYaml(locale.code); | |
}) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The intent of this was in a Nuxt.js app where we wanted to sync the Rails i18n YAML files into the UI at build time. This way the UI can ship with the locales separately from the back end rails app, while relieving us of putting locale data in two places.