Skip to content

Instantly share code, notes, and snippets.

@frixou89
Last active May 4, 2020 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frixou89/34d1579e5a41b3753533dba2e63ae4c7 to your computer and use it in GitHub Desktop.
Save frixou89/34d1579e5a41b3753533dba2e63ae4c7 to your computer and use it in GitHub Desktop.
NuxJS i18n export translation messages to json files
  • Install dependencies
npm install --save-dev cheerio glob
# or
yarn add -D cheerio glob
  • Create the file extract-i18n-json.js in the project's root directory

  • Create the export directory eg /i18n-json

  • Add script in your package.json

 "scripts": {
    "export-json": "node extract-i18n-json.js"
  },
const fs = require('fs')
const path = require('path')
const cheerio = require('cheerio')
const glob = require('glob')
const searchInPaths = ['./components', './pages', './layouts']
for (let d = 0; d < searchInPaths.length; d++) {
const _dir = searchInPaths[d]
glob(`${_dir}/**/*.vue`, {}, function(er, files) {
for (let f = 0; f < files.length; f++) {
exportFileTerms(files[f])
}
})
}
function exportFileTerms(fileToRead) {
fs.readFile(fileToRead, 'utf8', (err, contents) => {
// eslint-disable-next-line no-console
if (err) console.log(err)
const $ = cheerio.load(contents)
if ($('i18n').length) {
const fileName = path.basename(fileToRead).toLowerCase()
const t = $('i18n').text()
const parsed = JSON.parse(t)
if (parsed.en) {
fs.writeFileSync(
`i18n-json/${fileName}.json`,
JSON.stringify(parsed.en, null, 4)
)
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment