This repository has been archived by the owner on Oct 20, 2021. It is now read-only.
/
index.js
88 lines (76 loc) · 2.43 KB
/
index.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
79
80
81
82
83
84
85
86
87
88
"use strict";
const electron = require("electron");
const path = require("path");
const app = process.type === "browser" ? electron.app : electron.remote.app;
const appRelPath = path.relative(__dirname, app.getAppPath());
let rq = (module) => require.main.require(module);
let _electron = (module) => {
if (electron[module]) {
return electron[module];
} else if (process.type === "renderer" && electron.remote[module]) {
return electron.remote[module];
}
throw new Error(`${module} is not a valid electron module`);
};
let _remote = (module) => {
if (process.type === "renderer") {
return electron.remote.require(module);
} else {
// fallback on rq if process isnt renderer
return rq(module);
}
};
let _set = (arg1, arg2) => {
if (arg1 == null) throw Error("Undefined key is not allowed in rq.set()");
// Supports multiple declaration: [{ key, path }, { key, path }]
if (typeof arg1 === "object") {
for (let key in arg1) {
rq.set(key, arg1[key]);
}
} else {
let key = arg1;
// Replace template strings in path
const replaceStr = (str) => {
let re = /%{([A-Za-z]*)}/g;
let match;
const replaceValue = (fullStr, name) => {
let replacement = name === "app" ? app.getAppPath() : app.getPath(name);
return fullStr.replace(`%{${name}}`, replacement);
};
while ((match = re.exec(str)) !== null) {
str = replaceValue(str, match[1]);
}
return str;
};
let dir = replaceStr(arg2);
// Create the method
rq[key] = (module) => {
let modulePath;
if (!path.isAbsolute(dir)) {
modulePath = "./" + path.join(appRelPath, dir, module);
} else {
modulePath = path.join(dir, module);
}
return require(modulePath);
};
}
};
// Immutable properties
Object.defineProperties(rq, {
"electron": { value: _electron },
"remote": { value: _remote },
"set": { value: _set }
});
// Set default config
rq.set({
"root": "",
"renderer": "app/renderer",
"main": "app/main",
"browser": "app/main"
});
// Load custom config from package.json (if exists)
let pkg = rq.root("package.json");
if (pkg["electron-require"]) {
rq.set(pkg["electron-require"]);
}
module.exports = rq;