-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetModules.ts
102 lines (94 loc) · 2.85 KB
/
getModules.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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { getExportProps } from './ast';
import { readFileSync } from 'fs';
import { join } from 'path';
import glob from 'glob';
import { isStoreModule } from 'natur/dist/utils';
import { winPath } from '@umijs/utils';
type getModulesArg = {
srcPath: string;
relativePath: string;
isSyncModule: Function;
};
const firstCharToLowerCase = (str: string) =>
str.slice(0, 1).toLowerCase() + str.slice(1);
const getModules = ({ srcPath, relativePath, isSyncModule }: getModulesArg) => {
const storeModuleTargetDir = join(srcPath, relativePath);
let files = glob.sync(join(storeModuleTargetDir, '**', '*.{j,t}s'));
files = files.filter(fileName => !/\.d\.ts$/.test(fileName));
let filesObj = files
.map(f => {
const fileCode = readFileSync(f, 'utf-8');
const res = getExportProps(fileCode);
return {
fileName: f,
res: !!res && isStoreModule(res) ? res : null,
};
})
.filter(f => !!f.res)
.map(f => ({
relativePath: f.fileName.replace(srcPath, '@'),
absPath: winPath(f.fileName),
fileName: '',
customName: (f.res as any)?.name || '',
}));
filesObj = filesObj
.map(f => ({
...f,
fileName: f.relativePath
.replace(`@/${relativePath}`, '')
.slice(1)
// 删除扩展名
.replace(/\.(j|t)s$/, '')
// 删除 [, ] , $之类的特殊字符
.replace(/\[|\]|\$|\s/g, '')
// 将aaa/bbb/_c_cc的文件开头的 “_” 删除
.replace(/(\/)_/g, '$1')
.replace(/^\d+/, '')
// 将aaa/bbb/ccc改变为aaaBbbCcc
.replace(/[\/\-_]([a-zA-Z])/g, (_, s) => s.toUpperCase()),
}))
.map(f => ({
...f,
fileName: f.customName || firstCharToLowerCase(f.fileName),
}));
const fileNames = filesObj.map(f => f.fileName);
files = filesObj.map(f => f.relativePath);
const importModulesCode = fileNames
.reduce((res, fileName, index) => {
if (isSyncModule(files[index])) {
res =
res +
`import ${fileName} from '${filesObj[index].absPath.replace(
/\.(j|t)s$/,
'',
)}';\n`;
}
return res;
}, '')
.replace(/\n$/, '');
const modulesObjCode =
fileNames.reduce((res, fileName, index) => {
if (isSyncModule(files[index])) {
res = res + ` ${fileName},\n`;
}
return res;
}, '{\n') + '}';
const lazyModulesObjCode =
fileNames.reduce((res, fileName, index) => {
if (!isSyncModule(files[index])) {
res =
res +
` ${fileName}: () => import(/* webpackChunkName: "${fileName}" */ '${filesObj[
index
].absPath.replace(/\.(j|t)s$/, '')}'),\n`;
}
return res;
}, '{\n') + '}';
return {
importModulesCode,
modulesObjCode,
lazyModulesObjCode,
hasModules: !!fileNames.length,
};
};
export default getModules;