Created
March 31, 2022 07:05
-
-
Save nandenjin/92b1428a6f935394982cf46b0f53e4b7 to your computer and use it in GitHub Desktop.
Utilities for FormatJS -> poEdit -> Webpack
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
/** | |
* Quick converter from JSON by FormatJS to POT for translation utilities. | |
* stdin: JSON / stdout: POT | |
*/ | |
const potHeader = `msgid "" | |
msgstr "" | |
"Project-Id-Version: JV-Campus skanda\\n" | |
"Language: en_US\\n" | |
"MIME-Version: 1.0\\n" | |
"Content-Type: text/plain; charset=UTF-8\\n" | |
"Content-Transfer-Encoding: 8bit\\n" | |
` | |
;(() => { | |
let jsonStr = '' | |
process.stdin.on('data', (data) => { | |
jsonStr = data.toString() | |
}) | |
process.stdin.on('end', () => | |
process.stdout.write(convert(JSON.parse(jsonStr))) | |
) | |
const convert = (json) => { | |
let result = '' | |
for (const [, value] of Object.entries(json)) { | |
// Replace ids by FormatJS with original message, for convinience in translation. | |
// (It must be reveted by bundlers) | |
result += `msgid "${value.defaultMessage}"\n` | |
result += `msgstr ""\n` | |
result += `\n` | |
} | |
return potHeader + result | |
} | |
})() |
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
/** | |
* A Webpack Loader to load translated PO files | |
*/ | |
const crypto = require('crypto') | |
module.exports = (source) => { | |
// Add a line break to be matched with RegExp | |
source += '\n' | |
const result = {} | |
for (let [, id, str] of source.matchAll( | |
/msgid "([\s\S]*?)"[\r\n]msgstr "([\s\S]*?)"[\r\n][\r\n]/g | |
)) { | |
// Remove double quotations and line break to concat long messages | |
// (Long messages are separated by translation utilities as double quoted multi lines) | |
id = id.replace(/"\n"/g, '') | |
str = str.replace(/"\n"/g, '') | |
// Replace ids with SHA512-ed string | |
// (It reverts replacement in json2pot.js) | |
const hashId = crypto | |
.createHash('sha512') | |
.update(id, 'utf8') | |
.digest('base64') | |
.substring(0, 6) | |
result[hashId] = str | |
} | |
return `module.exports = ${JSON.stringify(result)}` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment