Skip to content

Commit

Permalink
scripts(i18n): support es modules in collect-strings (#12741)
Browse files Browse the repository at this point in the history
  • Loading branch information
connorjclark authored Jul 8, 2021
1 parent 000da66 commit f41ca8d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
18 changes: 11 additions & 7 deletions lighthouse-core/scripts/i18n/collect-strings.js
Original file line number Diff line number Diff line change
Expand Up @@ -521,9 +521,9 @@ function parseUIStrings(sourceStr, liveUIStrings) {
* Collects all LHL messsages defined in UIString from Javascript files in dir,
* and converts them into CTC.
* @param {string} dir absolute path
* @return {Record<string, CtcMessage>}
* @return {Promise<Record<string, CtcMessage>>}
*/
function collectAllStringsInDir(dir) {
async function collectAllStringsInDir(dir) {
/** @type {Record<string, CtcMessage>} */
const strings = {};

Expand All @@ -538,9 +538,9 @@ function collectAllStringsInDir(dir) {
if (!process.env.CI) console.log('Collecting from', relativeToRootPath);

const content = fs.readFileSync(absolutePath, 'utf8');
const exportVars = require(absolutePath);
const exportVars = await import(absolutePath);
const regexMatch = content.match(UISTRINGS_REGEX);
const exportedUIStrings = exportVars.UIStrings;
const exportedUIStrings = exportVars.UIStrings || (exportVars.default && exportVars.default.UIStrings);

if (!regexMatch) {
// No UIStrings found in the file text or exports, so move to the next.
Expand Down Expand Up @@ -674,14 +674,13 @@ function resolveMessageCollisions(strings) {
}
}

// Test if called from the CLI or as a module.
if (require.main === module) {
async function main() {
/** @type {Record<string, CtcMessage>} */
const strings = {};

for (const folderWithStrings of foldersWithStrings) {
console.log(`\n====\nCollecting strings from ${folderWithStrings}\n====`);
const moreStrings = collectAllStringsInDir(folderWithStrings);
const moreStrings = await collectAllStringsInDir(folderWithStrings);
Object.assign(strings, moreStrings);
}

Expand Down Expand Up @@ -715,6 +714,11 @@ if (require.main === module) {
console.log('✨ Complete!');
}

// Test if called from the CLI or as a module.
if (require.main === module) {
main();
}

module.exports = {
parseUIStrings,
createPsuedoLocaleStrings,
Expand Down
3 changes: 3 additions & 0 deletions report/renderer/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -645,3 +645,6 @@ if (typeof module !== 'undefined' && module.exports) {
} else {
self.Util = Util;
}

// TODO(esmodules): export these strings too, then collect-strings will work when this file is esm.
// export const UIStrings = Util.UIStrings;

0 comments on commit f41ca8d

Please sign in to comment.