|
1 | 1 | /** |
2 | 2 | * @file loader |
| 3 | + * @desc Insert route of skeleton into router.js, so that developer can |
| 4 | + * visit route path in dev mode to debug skeleton components |
3 | 5 | * @author panyuqi <panyuqi@baidu.com> |
4 | 6 | */ |
5 | 7 |
|
|
8 | 10 | const loaderUtils = require('loader-utils'); |
9 | 11 | const insertAt = require('./util').insertAt; |
10 | 12 |
|
| 13 | +const DEFAULT_LOADER_OPTIONS = { |
| 14 | + // template of importing skeleton component |
| 15 | + importTemplate: 'import [nameCap] from \'@/pages/[nameCap].vue\';', |
| 16 | + // template of route path |
| 17 | + routePathTemplate: '/skeleton-[name]', |
| 18 | + // position to insert route object in router.js file |
| 19 | + insertAfter: 'routes: [' |
| 20 | +}; |
| 21 | + |
11 | 22 | const ENTRY_NAME_HOLDER = /\[name\]/gi; |
12 | 23 | const ENTRY_NAME_CAP_HOLDER = /\[nameCap\]/gi; |
13 | 24 |
|
14 | 25 | module.exports = function (source) { |
15 | | - const options = loaderUtils.getOptions(this); |
| 26 | + const options = Object.assign({}, DEFAULT_LOADER_OPTIONS, loaderUtils.getOptions(this)); |
16 | 27 | let {entry, importTemplate, routePathTemplate, insertAfter} = options; |
17 | 28 |
|
18 | | - // position to insert in router.js |
| 29 | + // find position to insert in router.js |
19 | 30 | let routesPos = source.indexOf(insertAfter) + insertAfter.length; |
20 | 31 |
|
21 | | - if (!Array.isArray(entry)) { |
22 | | - entry = [entry]; |
23 | | - } |
| 32 | + entry = Array.isArray(entry) ? entry : [entry]; |
24 | 33 |
|
25 | 34 | entry.forEach(entryName => { |
26 | | - // capitalize first letter |
| 35 | + // capitalize first letter in entryName eg.skeleton -> Skeleton |
27 | 36 | let entryCap = entryName.replace(/([a-z])(.*)/, (w, firstLetter, rest) => firstLetter.toUpperCase() + rest); |
28 | | - // route path |
29 | | - let skeletonRoutePath = routePathTemplate.replace(ENTRY_NAME_HOLDER, entryName) |
30 | | - .replace(ENTRY_NAME_CAP_HOLDER, entryCap); |
31 | | - let importExpression = importTemplate.replace(ENTRY_NAME_HOLDER, entryName) |
32 | | - .replace(ENTRY_NAME_CAP_HOLDER, entryCap); |
| 37 | + |
| 38 | + // replace placeholder in routeTpl and importTpl |
| 39 | + let [skeletonRoutePath, importExpression] = [routePathTemplate, importTemplate] |
| 40 | + .map(pathStr => pathStr.replace(ENTRY_NAME_HOLDER, entryName) |
| 41 | + .replace(ENTRY_NAME_CAP_HOLDER, entryCap)); |
| 42 | + |
| 43 | + // route object to insert |
33 | 44 | let routeExpression = `{ |
34 | 45 | path: '${skeletonRoutePath}', |
35 | 46 | name: '${entryName}-skeleton', |
36 | 47 | component: ${entryCap} |
37 | 48 | },`; |
| 49 | + |
| 50 | + // insert route object into routes array |
38 | 51 | source = insertAt(source, routeExpression, routesPos); |
| 52 | + |
| 53 | + // insert import sentence in the head |
39 | 54 | source += importExpression; |
40 | 55 | }); |
41 | 56 |
|
|
0 commit comments