-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi18nExtractKeys.vite.js
More file actions
71 lines (59 loc) · 1.66 KB
/
i18nExtractKeys.vite.js
File metadata and controls
71 lines (59 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import path from "path";
import fs from "fs";
const uniqueKeys = new Set();
function extractRegexPlugin({ extraKeys } = {}) {
const fileOutput = path.join("registry", "uiLocaleKeysBackend.json");
/**
* Supported variants:
* this.t('key');
* {{ t('key') }}
* this.t(
* 'key'
* )
* To identify the translation keys, without triggering translation
* {'viewAction': tk('common.viewAction') }
*/
const regex = /(?:^|\W)tk?\([\s]*['"`](?<localeKey>[^'"`]+)['"`]/g;
extraKeys ||= [];
return {
name: "extract-keys",
transform(code, id) {
if (
!id.includes("node_modules") &&
(id.endsWith(".vue") || id.endsWith(".js"))
) {
const matches = [...code.matchAll(regex)];
for (const match of matches) {
uniqueKeys.add(match[1]);
}
}
return null;
},
buildEnd() {
for (const key of extraKeys) {
uniqueKeys.add(key);
}
// remove dummy key used in the comment examples
uniqueKeys.delete("key");
// remove keys with unresolved template literals
for (const key of uniqueKeys) {
if (key.includes("${")) {
uniqueKeys.delete(key);
}
}
if (uniqueKeys.size) {
const dir = path.dirname(fileOutput);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const outputArray = [...uniqueKeys].sort();
fs.writeFileSync(
fileOutput,
`${JSON.stringify(outputArray, null, 2)}\n`
);
console.log(`Written all existing locale keys to ${fileOutput}`);
}
},
};
}
module.exports = extractRegexPlugin;