-
Notifications
You must be signed in to change notification settings - Fork 18
/
generateEntryFiles.js
71 lines (52 loc) · 2.16 KB
/
generateEntryFiles.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
const path = require('path');
const fs = require('fs');
module.exports = function (pagesEntry) {
const outputPrefix = path.join(process.cwd(), '.megalo-h5-tmp');
!fs.existsSync(outputPrefix) && fs.mkdirSync(outputPrefix, { recursive: true });
const routeFilePath = path.join(outputPrefix, 'router.js'),
entryFilePath = path.join(outputPrefix, 'entry.js'),
appVuePath = path.join(outputPrefix, 'app.vue'),
htmlTemplatePath = path.join(outputPrefix, 'index.html');
// output routeFile, used in spa
const routeFile = generateRouteFile(pagesEntry);
fs.writeFileSync(routeFilePath, routeFile, { flag: 'w+' });
// copy entryFile, used in spa
!fs.existsSync(entryFilePath) && fs.copyFileSync(path.join(__dirname, './template/entry.js'), entryFilePath);
// copy app.vue, used in spa
!fs.existsSync(appVuePath) && fs.copyFileSync(path.join(__dirname, './template/app.vue'), appVuePath);
// copy index.html, used both in spa and mpa
!fs.existsSync(htmlTemplatePath) && fs.copyFileSync(path.join(__dirname, './template/index.html'), htmlTemplatePath);
}
function generateRouteFile (pagesEntry) {
let imports = [], route = [], output = [];
imports.push(`import Router from 'vue-router'`, `import Vue from 'vue'`)
let pageCount = 0;
let componentName;
const pages = Object.entries(pagesEntry)
for (const [key, value] of pages) {
pageCount++;
componentName = 'page' + pageCount;
imports.push(`import ${componentName} from '${value.replace(/.js$/, '.vue')}'`);
route.push(`{ path: '${getPath(key)}', component: ${componentName} }`);
}
route.push(`{ path: '/', component: page1 }`);
output.push(`Vue.use(Router);`, `
const router = new Router({
routes
})`, `export default router`)
return `
${imports.join('\n')}
const routes = [
${route.join(`,\n`)}
]
${output.join(`\n`)}
`
}
// add ’/‘ before route
function getPath (routePath) {
let newPath = routePath.trim();
if (!/^\//.test(newPath)) {
newPath = '/' + newPath;
}
return newPath;
}