@@ -44,7 +44,13 @@ export default (sourceDir, dataConfig, fields) => {
44
44
const routes = [ ]
45
45
46
46
const addRouters = template => {
47
- routes . push ( ` {
47
+ routes . push ( { name : `${ name } -${ template . type } ` , template } )
48
+ }
49
+
50
+ let routesLines = [ ]
51
+
52
+ const addRouterLines = template => {
53
+ routesLines . push ( ` {
48
54
path: '${ template . path } ',
49
55
name: '${ name } -${ template . type } ',
50
56
component: () => import('@/pages/${ name } /${ template . type } '),
@@ -90,9 +96,36 @@ export default (sourceDir, dataConfig, fields) => {
90
96
if ( err ) { }
91
97
92
98
const lines = data . split ( '\n' )
93
- console . log ( 'lines' , lines )
94
99
let count = 0
95
100
let codeIndex = 0
101
+
102
+ console . log ( 'routes' , routes )
103
+
104
+ // 删除无需重复生成的route
105
+ lines . forEach ( line => {
106
+ if ( line ) {
107
+ const trimedLine = line . replace ( / \s / g, '' )
108
+ if ( trimedLine . startsWith ( 'name:\'' ) ) {
109
+ // 取得route name
110
+ const routeName = trimedLine . substring ( 'name:\'' . length , trimedLine . lastIndexOf ( '\'' ) )
111
+ // 查找待生成的route列表中是否存在该route,存在则删除列表中的对应route
112
+ const index = routes . map ( route => route . name ) . indexOf ( routeName )
113
+ if ( index !== - 1 ) {
114
+ routes . splice ( index , 1 )
115
+ }
116
+ }
117
+ }
118
+ } )
119
+ console . log ( 'routes' , routes )
120
+ if ( routes . length === 0 ) {
121
+ return
122
+ }
123
+
124
+ routes . forEach ( route => {
125
+ addRouterLines ( route . template )
126
+ } )
127
+
128
+ // 倒查']',以便找到写入新代码地点
96
129
for ( let i = lines . length ; i > 0 ; i -- ) {
97
130
const line = lines [ i ]
98
131
if ( line && line . endsWith ( ']' ) ) {
@@ -108,7 +141,7 @@ export default (sourceDir, dataConfig, fields) => {
108
141
if ( ! line . endsWith ( ',' ) ) {
109
142
lines [ codeIndex ] = line + ','
110
143
}
111
- const newLines = lines . slice ( 0 , codeIndex + 1 ) . concat ( routes ) . concat ( lines . slice ( codeIndex + 1 ) )
144
+ const newLines = lines . slice ( 0 , codeIndex + 1 ) . concat ( routesLines ) . concat ( lines . slice ( codeIndex + 1 ) )
112
145
fs . writeFile ( routesPath , newLines . join ( '\n' ) , ( err ) => {
113
146
console . log ( `write ${ routesPath } . error: ${ err } ` )
114
147
} )
0 commit comments