jingrowtools/scripts/generate-prerender-routes.ts
2026-01-02 18:33:52 +08:00

109 lines
3.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 生成预渲染路由列表
* 从工具 store 中读取所有工具并生成对应的路由路径
*/
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import fs from 'node:fs'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
// 工具接口定义(与 store 中的 Tool 接口保持一致)
interface Tool {
id: string
toolName?: string
routePath?: string
type?: 'route' | 'url'
hidden?: boolean
}
// 读取默认工具列表(从 store 文件中提取)
function getDefaultTools(): Tool[] {
const toolsStorePath = resolve(__dirname, '../src/shared/stores/tools.ts')
const content = fs.readFileSync(toolsStorePath, 'utf-8')
const tools: Tool[] = []
// 使用正则表达式匹配工具对象定义
// 匹配模式:{ id: 'xxx', ..., toolName: 'xxx', ... }
const toolObjectRegex = /\{\s*id:\s*['"]([^'"]+)['"]([\s\S]*?)\}/g
let match
while ((match = toolObjectRegex.exec(content)) !== null) {
const toolBlock = match[0]
const id = match[1]
// 提取 toolName
const toolNameMatch = toolBlock.match(/toolName:\s*['"]([^'"]+)['"]/)
const toolName = toolNameMatch ? toolNameMatch[1] : null
// 提取 type默认为 'route'
const typeMatch = toolBlock.match(/type:\s*['"](route|url)['"]/)
const type = (typeMatch ? typeMatch[1] : 'route') as 'route' | 'url'
// 提取 hidden默认为 false
const hiddenMatch = toolBlock.match(/hidden:\s*(true|false)/)
const hidden = hiddenMatch ? hiddenMatch[1] === 'true' : false
// 提取 routePath如果存在
const routePathMatch = toolBlock.match(/routePath:\s*['"]([^'"]+)['"]/)
const routePath = routePathMatch ? routePathMatch[1] : undefined
if (toolName && type === 'route' && !hidden) {
tools.push({
id,
toolName,
routePath,
type,
hidden
})
}
}
return tools
}
// 生成所有需要预渲染的路由
function generatePrerenderRoutes(): string[] {
const defaultTools = getDefaultTools()
// 过滤出需要预渲染的工具(只包含 type 为 'route' 且未隐藏的工具)
const routes = defaultTools
.filter(tool => tool.type === 'route' && !tool.hidden)
.map(tool => {
// 使用 routePath 或根据 toolName 生成
if (tool.routePath) {
return `/${tool.routePath}`
}
if (tool.toolName) {
return `/tools/${tool.toolName.replace(/_/g, '-')}`
}
return `/tools/${tool.id.replace(/_/g, '-')}`
})
.filter((route, index, self) => self.indexOf(route) === index) // 去重
// 添加基础路由
const baseRoutes = [
'/',
'/tools'
]
return [...baseRoutes, ...routes]
}
// 如果直接运行此脚本,输出路由列表(用于调试)
if (import.meta.url === `file://${process.argv[1]}`) {
try {
const routes = generatePrerenderRoutes()
console.log('预渲染路由列表:')
routes.forEach(route => console.log(` - ${route}`))
console.log(`\n总共 ${routes.length} 个路由需要预渲染`)
} catch (error) {
console.error('生成预渲染路由失败:', error)
process.exit(1)
}
}
export { generatePrerenderRoutes }