forked from adrium/easypass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocaleLoader.js
78 lines (66 loc) · 1.69 KB
/
localeLoader.js
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
72
73
74
75
76
77
78
/*
* This Source Code is subject to the terms of the Mozilla Public License
* version 2.0 (the "License"). You can obtain a copy of the License at
* http://mozilla.org/MPL/2.0/.
*/
"use strict";
const fs = require("fs");
const path = require("path");
function walkDirectory(dir, callback)
{
return new Promise((resolve, reject) =>
{
fs.readdir(dir, {withFileTypes: true}, (err, files) =>
{
if (err)
{
reject(err);
return;
}
let subdirs = [];
for (let file of files)
{
let filePath = path.join(dir, file.name);
if (file.isDirectory())
subdirs.push(walkDirectory(filePath, callback));
else if (file.isFile && file.name.endsWith(".json"))
callback(filePath);
}
resolve(Promise.all(subdirs));
});
});
}
module.exports = function(localeRoot)
{
return {
name: "locale-loader",
resolveId(id)
{
return id == "locale" ? id : null;
},
load(id)
{
if (id != "locale")
return null;
let locale = {};
return walkDirectory(localeRoot, file =>
{
let parts = path.relative(localeRoot, file).split(path.sep);
let fileName = parts.pop();
if (!fileName.startsWith("_"))
parts.push(path.basename(fileName, ".json"));
let prefix = "";
if (parts.length)
prefix = parts.join("@") + "@";
let data = JSON.parse(fs.readFileSync(file, {
encoding: "utf-8"
}));
for (let name of Object.keys(data))
locale[prefix + name] = data[name];
}).then(() =>
{
return "export default " + JSON.stringify(locale, null, 2);
});
}
};
};