Skip to content

Commit faca7cc

Browse files
committed
refactor(i18n): lazy load translation
1 parent d7ab435 commit faca7cc

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

source/i18n.ts

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,32 @@ const baseStr = fs.readFileSync(path.join(localeDir, 'en.yaml'), {
99
encoding: 'utf8'
1010
});
1111

12-
fs.readdirSync(localeDir)
12+
const codes = fs
13+
.readdirSync(localeDir)
1314
.filter((i) => i.endsWith('.yaml'))
1415
.map((i) => {
15-
const code = i.substr(0, i.length - 5);
16-
result[code] = Object.assign(
17-
yaml.safeLoad(baseStr),
18-
yaml.safeLoad(
19-
fs.readFileSync(path.join(localeDir, `${code}.yaml`), {
20-
encoding: 'utf8'
21-
})
22-
)
23-
) as I18nLang;
24-
return code;
16+
return i.substr(0, i.length - 5);
2517
});
2618

19+
const cache = new Map<string, I18nLang>();
20+
for (const code of codes) {
21+
Object.defineProperty(result, code, {
22+
enumerable: true,
23+
get(): I18nLang {
24+
if (!cache.has(code)) {
25+
const translation = Object.assign(
26+
yaml.safeLoad(baseStr),
27+
yaml.safeLoad(
28+
fs.readFileSync(path.join(localeDir, `${code}.yaml`), {
29+
encoding: 'utf8'
30+
})
31+
)
32+
) as I18nLang;
33+
34+
cache.set(code, translation);
35+
}
36+
return cache.get(code);
37+
}
38+
});
39+
}
2740
export default result;

0 commit comments

Comments
 (0)