This repository was archived by the owner on Dec 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathsky-pages-component-generator.js
68 lines (57 loc) · 1.88 KB
/
sky-pages-component-generator.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
/*jshint node: true*/
'use strict';
const fs = require('fs');
const glob = require('glob');
const path = require('path');
function generateImport(component) {
const definition =
`// BEGIN IMPORTED COMPONENT: ${component.componentName}
import { ${component.componentName} } from '${component.importPath}';
// END IMPORTED COMPONENT: ${component.componentName}`;
return definition;
}
function extractComponentName(file) {
const content = fs.readFileSync(file, { encoding: 'utf8' });
const matches = content.split(/@Component\s*\([\s\S]+?\)\s*export\s+class\s+(\w+)/g);
switch (matches.length) {
case 3:
return matches[1];
case 1:
case 2:
throw new Error(`Unable to locate an exported class in ${file}`);
default:
throw new Error(`As a best practice, please export one component per file in ${file}`);
}
}
function generateImports(components) {
return components
.map(component => generateImport(component))
.join('\n\n');
}
function generateNames(components) {
return components.map(component => component.componentName);
}
function generateComponents(skyAppConfig) {
// Prepend the alias and remove the file extension,
// since the file extension causes a TypeScript error.
return glob
.sync(path.join(skyAppConfig.runtime.srcPath, skyAppConfig.runtime.componentsPattern), {
ignore: [
path.join(skyAppConfig.runtime.srcPath, skyAppConfig.runtime.componentsIgnorePattern)
]
})
.map(file => ({
importPath: skyAppConfig.runtime.spaPathAlias + '/' + file.replace(/\.[^\.]+$/, ''),
componentName: extractComponentName(file)
}));
}
function getComponents(skyAppConfig) {
const components = skyAppConfig.runtime.components || generateComponents(skyAppConfig);
return {
imports: generateImports(components),
names: generateNames(components)
};
}
module.exports = {
getComponents: getComponents
};