Skip to content

Commit

Permalink
feat: add useParams for every route
Browse files Browse the repository at this point in the history
  • Loading branch information
baozouai committed Jul 21, 2023
1 parent 55c6b4b commit 7866b6b
Show file tree
Hide file tree
Showing 10 changed files with 111 additions and 64 deletions.
1 change: 1 addition & 0 deletions playgrounds/react-router-5-js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"@types/react-dom": "^18.2.5",
"@types/react-router": "5.1.20",
"@types/react-router-dom": "5.3.3",
"babel-loader": "^9.1.2",
"html-webpack-plugin": "^5.5.3",
"ts-loader": "^9.4.3",
"typescript": "^4.9.5",
Expand Down
5 changes: 3 additions & 2 deletions playgrounds/react-router-5/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,13 @@
"@types/react-dom": "^18.2.5",
"@types/react-router": "5.1.20",
"@types/react-router-dom": "5.3.3",
"babel-loader": "^9.1.2",
"generate-history-method-webpack-plugin": "workspace:*",
"html-webpack-plugin": "^5.5.3",
"ts-loader": "^9.4.3",
"typescript": "^4.9.5",
"webpack": "^5.87.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1",
"generate-history-method-webpack-plugin": "workspace:*"
"webpack-dev-server": "^4.15.1"
}
}
4 changes: 2 additions & 2 deletions playgrounds/react-router-5/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ function Layout() {
</li>
<li
style={commonLiStyle}
onClick={() => history.OPEN_MY()}
onClick={() => history.REPLACE_MY()}
>
REPLACE_MY
</li>
Expand All @@ -100,7 +100,7 @@ function Layout() {
{
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
routePaths.filter(({ path }) => !['/order', '/order/detail', '/my'].includes(path)).map(({ path }) => {
const name = path.slice(1).toUpperCase().replace(/\//g, '_')
const name = path.slice(1).toUpperCase().replace(/\s/g, '').replace(/[^\w]/g, '_').replace(/_{2,}/g, '_')
return (
<ul key={name}>
<li
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export default interface Params {
order_id: string
/** 随便写的订单类型 */
order_type: 'CREATE' | 'UPDATE' | 'DELETE'
}

}
9 changes: 4 additions & 5 deletions playgrounds/react-router-5/src/pages/order/xxx/index.page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { useParams } from 'react-router'
import { history } from '~history'
export default () => {
const params = useParams()
console.log(params)

const params = history.useORDER_XXX_PARAMS()
console.log(params.xxx_id)
return (
<div>这是order 的xxx</div>
<div>这是order 的xxx1</div>
)
}
8 changes: 8 additions & 0 deletions playgrounds/react-router-5/src/pages/order/~ q/index.page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { history } from '~history'
export default () => {
console.log(history.useORDER_Q_PARAMS().id)

return (
<div>这是order 的~ q111</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default interface Params {
/** 这是id */
id: string

}
4 changes: 1 addition & 3 deletions playgrounds/react-router-5/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,7 @@ module.exports = {
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
new GenerateHistoryMethodWebpackPlugin({
originHistoryModuleName: isHash ? '@/hash_history' : '@/browser_history',
}),
new GenerateHistoryMethodWebpackPlugin(),
// ...其他插件
],
devServer: {
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

130 changes: 79 additions & 51 deletions src/generate-history-method-webpack-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class GenerateHistoryMethodWebpackPlugin {
contents: string[] = []
reactRouterVersion: AllowReactRouterVersion
exportHistoryName: string

isExistTS = false
getDefaultConfig() {
if (existsSync(CONFIG_FILE_PATH)) {
// @ts-ignore
Expand Down Expand Up @@ -115,8 +115,13 @@ class GenerateHistoryMethodWebpackPlugin {
return this.mode === 'hash'
}

get iVersion6() {
return this.reactRouterVersion === 6
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() {
Expand All @@ -127,46 +132,25 @@ class GenerateHistoryMethodWebpackPlugin {
console.warn(err)
return
}
const isExistTS = files.some(file => /\.tsx?/.test(extname(file)))
this.isExistTS = files.some(file => /\.tsx?/.test(extname(file)))
this.contents = []

this.addTopImport()
this.generateUseHistoryHook(isExistTS)
this.generateRouter(isExistTS)
this.generateUseHistoryHook()
this.generateUseSearchParamsHook()
this.generateRouter()

const { urlObj, paramsMap } = this.getParamsMapAndUrlObj(files)
const urlKeys = Object.keys(urlObj)
const formatUrls = Object.keys(urlObj)

this.generateURL_MAP(urlObj)
this.generateFormatUrlFn(isExistTS)
this.generateHistory(paramsMap, urlKeys, isExistTS)
this.generateUseSearchParamsHook(isExistTS)
this.generateFormatUrlFn()
this.generateHistory(paramsMap, formatUrls)

this.contents.unshift('// @eslint-ignored')
const contentStr = this.contents.join('\n')
const outputPath = resolve(
cwdPath,
`node_modules/${this.historyModuleName}.${isExistTS ? 'tsx' : 'js'}`,
) // 输出文件路径
if (existsSync(outputPath)) {
// 已存在则对比是否变化,没变化则没必要写入
const originFile = readFileSync(outputPath, 'utf-8')
if (originFile === contentStr)
return
}
writeFileSync(outputPath, contentStr)
})
}
this.contents.unshift('/* eslint-disable */')

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()
},
)
this.generateFile()
})
}

addTopImport() {
Expand All @@ -178,7 +162,7 @@ class GenerateHistoryMethodWebpackPlugin {
)
}

generateUseHistoryHook(isExistTS: boolean) {
generateUseHistoryHook() {
this.contents.push(`
export const useRouterHistory = () => {
const historyRef = useRef(originHistory)
Expand All @@ -192,12 +176,13 @@ export const useRouterHistory = () => {
// @ts-ignore
history.listen(setState)
}, [history])
return [history, state] ${isExistTS ? 'as [typeof history, typeof state]' : ''}
return [history, state] ${this.isExistTS ? 'as [typeof history, typeof state]' : ''}
}
`)
}

generateUseSearchParamsHook(isExistTS: boolean) {
generateUseSearchParamsHook() {
const isExistTS = this.isExistTS
this.contents.push(`
export function useSearchParams${isExistTS ? '<T = any>' : ''}() {
const { search } = useLocation()
Expand All @@ -206,11 +191,12 @@ export function useSearchParams${isExistTS ? '<T = any>' : ''}() {
`)
}

generateRouter(isExistTS: boolean) {
generateRouter() {
const isExistTS = this.isExistTS
switch (this.reactRouterVersion) {
case 5:
this.contents.push(`
export function Router({ children }${isExistTS ? ':{children: ReactNode}' : ''}) {
export function Router({ children }${isExistTS ? ':{ children: ReactNode }' : ''}) {
return (
<BaseRouter
// @ts-ignore
Expand All @@ -229,7 +215,7 @@ ${isExistTS
basename?: string;
children?: ReactNode;
}`
: ''}
: ''}
export function Router({ children, basename }${isExistTS ? ': RouterProps' : ''}) {
const [history, { action, location }] = useRouterHistory()
// 一般变化的就是action和location
Expand All @@ -255,16 +241,28 @@ export function Router({ children, basename }${isExistTS ? ': RouterProps' : ''}
}

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()
.replace(/\//g, '_') || '$INDEX' // 首页
// 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)
Expand All @@ -285,44 +283,74 @@ export function Router({ children, basename }${isExistTS ? ': RouterProps' : ''}
)
}

generateFormatUrlFn(isExistTS: boolean) {
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>, urlKeys: string[], isExistTS: boolean) {
generateHistory(paramsMap: Record<string, string>, formatUrls: string[]) {
const isExistTS = this.isExistTS
const methods: string[] = []
const PathParamsTypeArrs: string[] = []
for (const urlKey of urlKeys) {
if (paramsMap[urlKey]) {

for (const formatUrl of formatUrls) {
const possibleParamsPath = paramsMap[formatUrl]
if (possibleParamsPath) {
PathParamsTypeArrs.push(
`import ${urlKey}_Params from '${paramsMap[urlKey]}'`,
`import ${formatUrl}_Params from '${possibleParamsPath}'`,
)
}
let queryType = ''
if (isExistTS)
queryType = `?: ${paramsMap[urlKey] ? `${urlKey}_Params` : 'any'}`
queryType = `?: ${possibleParamsPath ? `${formatUrl}_Params` : 'any'}`

const realUrl = `URL_MAP['${urlKey}']`
const realUrl = `URL_MAP['${formatUrl}']`

methods.push(
` TO_${urlKey}: (query${queryType}) => {
` TO_${formatUrl}: (query${queryType}) => {
originHistory.push(formatUrlFn(${realUrl}, query))
},`,
` OPEN_${urlKey}: (query${queryType}) => {
` OPEN_${formatUrl}: (query${queryType}) => {
window.open(formatUrlFn('${this.isHash ? '#' : ''}' + ${realUrl}, query))
},`,
` REPLACE_${urlKey}: (query${queryType}) => {
` 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

0 comments on commit 7866b6b

Please sign in to comment.