-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate-history-method-webpack-plugin.ts
359 lines (327 loc) · 10.2 KB
/
generate-history-method-webpack-plugin.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import { existsSync, readFileSync, writeFileSync } from 'fs'
import { dirname, extname, resolve } from 'path'
import { validate } from 'schema-utils'
import glob from 'glob'
import schema from './schema.json'
import { CONFIG_FILE_PATH } from './const'
const cwdPath = process.cwd()
type HistoryMode = 'hash' | 'browser'
type AllowReactRouterVersion = 5 | 6
interface GenerateHistoryMethodWebpackPluginOptions {
/**
* @description The name of the file defining the route parameter type, must be .ts
* @default index.params
* */
paramsName?: string
/**
* @description Identify is the filename of the routed page
* @default index.page
*/
pageName?: string
/**
* whitch module you want to import
* @default ~history
* @example
* import history from '~history'
*/
historyModuleName?: string
/**
* your origin history import from whitch module.
*
* for example, if you import history from 'history',
*
* so the originHistoryModuleName is 'history'
* @default 'history'
*/
originHistoryModuleName?: string
/**
* @description the history name you want to custom
* @default history
* @example
* { exportHistoryName: 'myHistory' }
* import { myHistory } from '~history'
* */
exportHistoryName?: string
/**
* your pages path root
* @example
* path.resolve(cwdPath, 'src/pages') */
pagesRootPath: string
/**
* hash or brower
* @default 'browser'
*/
mode?: HistoryMode
/** the react router version */
reactRouterVersion: AllowReactRouterVersion
}
class GenerateHistoryMethodWebpackPlugin {
paramsName: string
pageName: string
historyModuleName: string
originHistoryModuleName: string
pagesRootPath: string
mode: HistoryMode
contents: string[] = []
reactRouterVersion: AllowReactRouterVersion
exportHistoryName: string
isExistTS = false
getDefaultConfig() {
if (existsSync(CONFIG_FILE_PATH)) {
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-var-requires
const config = require(CONFIG_FILE_PATH)
return config as GenerateHistoryMethodWebpackPluginOptions
}
return {}
}
combindConfig(config: GenerateHistoryMethodWebpackPluginOptions) {
const defaultConfig = this.getDefaultConfig()
return {
...defaultConfig,
...config,
}
}
constructor(options = {} as GenerateHistoryMethodWebpackPluginOptions) {
const combineOptions = this.combindConfig(options)
const {
paramsName = 'index.params',
pageName = 'index.page',
historyModuleName = '~history',
originHistoryModuleName = 'history',
mode = 'browser',
exportHistoryName = 'history',
pagesRootPath,
reactRouterVersion,
} = combineOptions
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
validate(schema as any, combineOptions)
this.paramsName = paramsName
this.pageName = pageName
this.historyModuleName = historyModuleName
this.originHistoryModuleName = originHistoryModuleName
this.pagesRootPath = pagesRootPath
if (this.pagesRootPath.includes('\\'))
this.pagesRootPath = this.pagesRootPath.replace(/\\/g, '\/')
this.mode = mode
this.reactRouterVersion = reactRouterVersion
this.exportHistoryName = exportHistoryName
}
get isHash() {
return this.mode === 'hash'
}
apply(compiler: any) {
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
compiler.hooks.beforeCompile.tap(
GenerateHistoryMethodWebpackPlugin.name,
() => this.run(),
)
}
run() {
const filePattern = `${this.pagesRootPath}/**/${this.pageName}.{tsx,js,jsx}` // 匹配的文件模式
glob(filePattern, (err, files) => {
if (err) {
console.warn(err)
return
}
this.isExistTS = files.some(file => /\.tsx?/.test(extname(file)))
this.contents = []
this.addTopImport()
this.generateUseHistoryHook()
this.generateUseSearchParamsHook()
this.generateRouter()
const { urlObj, paramsMap } = this.getParamsMapAndUrlObj(files)
const formatUrls = Object.keys(urlObj)
this.generateURL_MAP(urlObj)
this.generateFormatUrlFn()
this.generateHistory(paramsMap, formatUrls)
this.contents.unshift('/* eslint-disable */')
this.generateFile()
})
}
addTopImport() {
this.contents.push(
'import React, { useLayoutEffect, useRef, useState, ReactNode } from \'react\'',
'import { useLocation, Router as BaseRouter } from \'react-router-dom\'',
`import originHistory from '${this.originHistoryModuleName}'`,
'import qs from \'qs\'\n',
)
}
generateUseHistoryHook() {
this.contents.push(`
export const useRouterHistory = () => {
const historyRef = useRef(originHistory)
const history = historyRef.current
const [state, setState] = useState({
action: history.action,
location: history.location,
})
useLayoutEffect(() => {
// @ts-ignore
history.listen(setState)
}, [history])
return [history, state] ${this.isExistTS ? 'as [typeof history, typeof state]' : ''}
}
`)
}
generateUseSearchParamsHook() {
const isExistTS = this.isExistTS
this.contents.push(`
export function useSearchParams${isExistTS ? '<T = any>' : ''}() {
const { search } = useLocation()
return qs.parse(search, { ignoreQueryPrefix: true }) ${isExistTS ? 'as T' : ''}
}
`)
}
generateRouter() {
const isExistTS = this.isExistTS
switch (this.reactRouterVersion) {
case 5:
this.contents.push(`
export function Router({ children }${isExistTS ? ':{ children: ReactNode }' : ''}) {
return (
<BaseRouter
// @ts-ignore
children={children}
// @ts-ignore
history={originHistory}
/>
)
}`,
)
break
case 6:
this.contents.push(`
${isExistTS
? `export interface RouterProps {
basename?: string;
children?: ReactNode;
}`
: ''}
export function Router({ children, basename }${isExistTS ? ': RouterProps' : ''}) {
const [history, { action, location }] = useRouterHistory()
// 一般变化的就是action和location
return (
<BaseRouter
basename={basename}
children={children}
location={location}
// @ts-ignore
navigationType={action}
// @ts-ignore
action={action}
// @ts-ignore
navigator={history}
// @ts-ignore
history={history}
/>
)
}`,
)
break
}
}
getParamsMapAndUrlObj(files: string[]) {
// { formatPath => paramsPath }
const paramsMap: Record<string, string> = {}
const regExp = new RegExp(`[\/\\\\]${this.pageName.replace(/(?=\.)/g, '\\')}\.(tsx|jsx?)$`)
// { formatPath => urlPath }
const urlObj = files.reduce<Record<string, string>>((pre, path) => {
// eg: path: Users/xxx/project/src/pages/order/ ~ q/index.page.tsx
const urlPath = path
// eg: /order/ ~ q/index.page.tsx
.replace(this.pagesRootPath, '')
// eg: /order/ ~ q/index.page.tsx => /order/ ~ q
.replace(regExp, '') || '/'
const formatPath = urlPath
// eg: /order/ ~ q => order/ ~ q
.slice(1)
// eg: order/~ q => ORDER/ ~ Q
.toUpperCase()
// eg: ORDER/ ~ Q => ORDER/~Q
.replace(/\s/g, '')
// eg: ORDER/~Q => ORDER__Q
.replace(/[^\w]/g, '_')
// eg: ORDER__Q => ORDER_Q
.replace(/_{2,}/g, '_') || '$INDEX' // 首页
pre[formatPath] = urlPath
const dir = dirname(path)
const possibleParamsPath = resolve(
dir,
`${this.paramsName}.ts`,
)
if (existsSync(possibleParamsPath))
paramsMap[formatPath] = possibleParamsPath.replace(/\\/g, '\/').replace('.ts', '')
return pre
}, {})
return { paramsMap, urlObj }
}
generateURL_MAP(urlObj: Record<string, string>) {
this.contents.push(
`export const URL_MAP = ${JSON.stringify(urlObj, null, 2)}\n`,
)
}
generateFormatUrlFn() {
const isExistTS = this.isExistTS
this.contents.push(
`const formatUrlFn = (path${isExistTS ? ': string' : ''}, query${isExistTS ? ': any' : ''}) => path + (query ? \'?\' + qs.stringify(query || {}): \'\')`,
)
}
generateHistory(paramsMap: Record<string, string>, formatUrls: string[]) {
const isExistTS = this.isExistTS
const methods: string[] = []
const PathParamsTypeArrs: string[] = []
for (const formatUrl of formatUrls) {
const possibleParamsPath = paramsMap[formatUrl]
if (possibleParamsPath) {
PathParamsTypeArrs.push(
`import ${formatUrl}_Params from '${possibleParamsPath}'`,
)
}
let queryType = ''
if (isExistTS)
queryType = `?: ${possibleParamsPath ? `${formatUrl}_Params` : 'any'}`
const realUrl = `URL_MAP['${formatUrl}']`
methods.push(
` TO_${formatUrl}: (query${queryType}) => {
originHistory.push(formatUrlFn(${realUrl}, query))
},`,
` OPEN_${formatUrl}: (query${queryType}) => {
window.open(formatUrlFn('${this.isHash ? '#' : ''}' + ${realUrl}, query))
},`,
` REPLACE_${formatUrl}: (query${queryType}) => {
originHistory.replace(formatUrlFn(${realUrl}, query))
},`,
)
if (isExistTS && possibleParamsPath) {
methods.push(
` use${formatUrl}_PARAMS: () => useSearchParams${`<${formatUrl}_Params>`}(),`,
)
}
}
this.contents.unshift(...PathParamsTypeArrs)
this.contents.push(`export const ${this.exportHistoryName} = {`)
this.contents.push(...methods)
this.contents.push('}\n')
}
generateFile() {
const contentStr = this.contents.join('\n')
const possibleOutputPath = ['tsx', 'js'].map(ext => resolve(
cwdPath,
`node_modules/${this.historyModuleName}.${ext}`,
))
const outputPath = resolve(
cwdPath,
`node_modules/${this.historyModuleName}.${this.isExistTS ? 'tsx' : 'js'}`,
)
if (existsSync(outputPath)) {
// 已存在则对比是否变化,没变化则没必要写入
const originFile = readFileSync(outputPath, 'utf-8')
if (originFile === contentStr)
return
}
writeFileSync(outputPath, contentStr)
}
}
export default GenerateHistoryMethodWebpackPlugin