-
Notifications
You must be signed in to change notification settings - Fork 3
/
addMainContext.ts
41 lines (37 loc) · 1.27 KB
/
addMainContext.ts
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
import fs from "fs";
import { err } from "./const";
let filePath = '';
const getFilePath = function (filePath: string, name: string) {
let afterPath = filePath.split('src')[1];
afterPath = afterPath.replace('\\', '/');
return './src' + afterPath + '/' + name;
}
const addContext = (args: string[], name: string) => {
let importsHeader = `import ${name} from "${getFilePath(filePath, name)}";\r\n`;
if (args[0].includes(importsHeader)) {
err(name + '已导入!');
return
}
let imports = args[0] + importsHeader;
let contexts = args[1].split('{');
let ctx = contexts[0] + `{\r\n${name},` + contexts[1];
let defaultContexts = args[2].split('{')
let ctxs = defaultContexts[0] + `{\r\n${name},` + defaultContexts[1];
return [imports, ctx, ctxs].join('export');
}
const writeFile = (context: string) => {
fs.writeFile('./main.ts', context, (error) => {
console.error(error);
})
}
export default (path: string, name: string) => {
filePath = path
fs.readFile('./main.ts', 'utf-8', (readError, data) => {
if (readError) {
console.error(readError);
return;
}
let context = addContext(data.split('export'), name);
context ? writeFile(context) : null
})
}