扩展
通过一些示例来满足你的项目需求
排除页面
当 exclude 参数无法排除某些页面时,可以通过 onAfterScanPages 钩子来对扫描的页面进行过滤
vite.config.js
util.js
import UniPages from '@uni-helper/vite-plugin-uni-pages'
import { defineConfig } from 'vite'
import { scanPageFilter } from './builds/util.js'
export default defineConfig({
plugins: [
UniPages({
onAfterScanPages: (ctx) => {
// 扫描页面后进行过滤
scanPageFilter(ctx, 'pages')
scanPageFilter(ctx, 'subPages')
},
})
],
})
export function scanPageFilter(ctx, inKey) {
if (!(inKey in ctx)) return
const keysToRemove = []
for (const key of ctx[inKey].keys()) {
// 只有以 .page.vue 结尾的页面会被保留
if (!key.endsWith('.page.vue')) {
keysToRemove.push(key)
}
}
keysToRemove.forEach((key) => {
ctx[inKey].delete(key)
})
}
路由唯一标识
在普遍业务场景中,路由需要一个唯一标识 name,即路由名称,但有时我们并不想手动为每个页面配置 name,这时可以通过 onAfterMergePageMetaData 钩子来自动生成
vite.config.js
util.js
import UniPages from '@uni-helper/vite-plugin-uni-pages'
import { defineConfig } from 'vite'
import { handlePageName } from './builds/util.js'
export default defineConfig({
plugins: [
UniPages({
onAfterMergePageMetaData: (ctx) => {
handlePageName(ctx, 'pageMetaData')
handlePageName(ctx, 'subPageMetaData')
},
})
],
})
export function handlePageName(ctx, inKey) {
if (!(inKey in ctx)) return
ctx[inKey].forEach((page) => {
// 配置优先级高于自动生成
if (page.name) return
// 将路径中的 /.- 替换为下划线,并转换为大写,作为路由名称
// 例如:路径 pages/home/index.page.vue 会生成路由名称 PAGES_HOME_INDEX_PAGE
// 你可以根据需要修改生成规则,建议通过 path 转化而成,大多数情况下能保持全局唯一,而且容易从 name 猜测页面所在
page.name = page.path.replace(/[/.-]/g, '_').toUpperCase()
})
}
路径常量化
为了避免硬编码,路径常量化往往能够提升开发体验,在 onAfterWriteFile 钩子中,读取最终所有页面数据,生成路径常量化模块
vite.config.js
util.js
import UniPages from '@uni-helper/vite-plugin-uni-pages'
import { defineConfig } from 'vite'
import { writePageConst } from './builds/util.js'
export default defineConfig({
plugins: [
UniPages({
onAfterWriteFile: (ctx) => {
writePageConst(ctx)
},
})
],
})
import fs from 'node:fs'
import { fileURLToPath, URL } from 'node:url'
import * as prettier from 'prettier'
// prettier 插件,用于排序 import 语句,不需要可移除
import * as prettierPluginSortImports from '@ianvs/prettier-plugin-sort-imports'
export async function writePageConst(ctx) {
const pageConstEntries = []
;[...ctx.pageMetaData, ...ctx.subPageMetaData].forEach((page) => {
// 使用标题作为注释
const comment = `/** ${page.style?.navigationBarTitleText || ''} */`
// name 作为唯一键
pageConstEntries.push(`${comment}\n"${page.name}": "/${page.path}",\n`)
})
// 如果你是 ts 项目,可以对照参考改为 enum 或者其他形式
const fileContent = `
/*******************************
* 此文件由脚本自动生成,请勿手动修改 *
*******************************/
/**
* 页面路径常量
*/
export const PageUrlConst = {\n${pageConstEntries.join('\n')}\n}
`
const filepath = fileURLToPath(new URL('../constants/pageConst.js', import.meta.url))
try {
// 如果你不需要 prettier 美化代码,可以跳过该步骤,直接写入文件
const prettierConfig = await prettier.resolveConfig(filepath)
const formattedContent = prettier.format(fileContent, {
...prettierConfig,
filepath,
plugins: [prettierPluginSortImports],
})
fs.writeFileSync(filepath, formattedContent, {
encoding: 'utf-8',
})
console.log(`✅ 页面路径常量文件已成功生成:${filepath}`)
} catch (error) {
console.error(`❌ 生成页面路径常量文件失败:${error.message}`)
console.error('错误详情:', error)
}
}