Nuxt 3.6.1与Nuxt Content 2.7.0动态路由构建报错求助
Nuxt 3.6.1 + Nuxt Content 2.7.0动态路由生成报错:TypeError: route.split is not a function
问题背景
升级Nuxt至3.6.1、Nuxt Content至2.7.0版本后,原有动态路由生成逻辑失效。执行npm run build时,nuxt.config.js中用于生成动态路由的函数抛出TypeError: route.split is not a function错误,按官方文档修改代码后问题仍未解决。
报错信息
├─ async routes() { nitro 11:11:07 AM const { $content } = require('@nuxt/content'); const files = await $content({ deep: true }).only(['path']).fetch(); return files.map((file) => { let filePath = file.path; if (filePath === '/pages/index' || filePath.includes('/site')) { filePath = '/'; } else if (filePath.includes('/pages')) { filePath = filePath.toString().split('/pages')[1].split('/index')[0]; } return filePath; }); } (undefinedms) (TypeError: route.split is not a function)
原配置代码
generate: { fallback: true, // 生成动态链接 async routes() { const { $content } = require('@nuxt/content') const files = await $content({ deep: true }).only(['path']).fetch() return files.map((file) => { let filePath = file.path if (filePath === '/pages/index' || filePath.includes('/site')) { filePath = '/' } else if (filePath.includes('/pages')) { filePath = filePath.toString().split('/pages')[1].split('/index')[0] } return filePath }) } },
按官方文档修改后的代码
const { $content } = require('@nuxt/content') const files = await $content({ deep: true }).only(['path']).fetch() return files.map(file => file.path === '/pages/index' ? '/' : file.path)
解决方法
问题核心是Nuxt 3已废弃Nuxt 2的generate配置,需改用Nitro预渲染配置,同时调整内容查询方式:
- 迁移配置位置:将路由生成逻辑移至
nitro.prerender.routes下 - 使用正确的内容查询API:Nuxt 3 Content推荐使用
#content/server提供的serverContentQuery获取文件
修改后的nuxt.config.js代码:
export default defineNuxtConfig({ nitro: { prerender: { async routes() { // 导入服务端内容查询API const { serverContentQuery } = await import('#content/server') // 获取所有内容文件的path字段 const files = await serverContentQuery('', { deep: true, only: ['path'] }) return files.map(file => { // 避免path不存在的情况 if (!file.path) return '' let filePath = file.path if (filePath === '/pages/index' || filePath.includes('/site')) { return '/' } else if (filePath.includes('/pages')) { // 处理路径时确保返回合法字符串 const processedPath = filePath.split('/pages')[1].split('/index')[0] return processedPath || '/' } return filePath }) } } } })
额外注意事项
- 确保所有返回的路由均为字符串类型,避免返回undefined或非字符串值
- 若仍有问题,可检查内容文件的
path字段是否存在异常值(比如非字符串类型)
内容的提问来源于stack exchange,提问作者Otto
相关产品推荐
相关产品推荐

