-2

I have a structure like this:

pages:
  - route1
     - lots of js page
  - index.js

I would like to display a list of all pages under route1 on my index page.

How can I fetch all available pages?

I tried to use getStaticProps in index to load all the files using fs and path but I am not able to require all the pages.

export async function fetchPages() {
    const fs = require('fs')
    const path = require('path')

    const files = fs.readdirSync(path.join(process.cwd(), '/pages/route1/'))


    return map(files, (f) => {
        return require(path.join(process.cwd(), '/pages/route1/', f))
    })
}

but this is not working.

Edit: require is used to load all the export from those pages such as title of the page or excerpt to display on the index page.

Edit: The error is Error: Cannot find module '/path/to/pages/route1/pageName.js'. Coming from the require.

Edit: I tried to use How to generate a menu based on the files in the pages directory in Next.js but it does not work since in the next config file we have to use require/module.export but the require('path/to/page') is going to bring react pages with imports and exports

Wonay
  • 1,160
  • 13
  • 35

1 Answers1

0

Can you create a page variable as an Array and push routes ?

const fs = require('fs')
const path = require('path')

const pages = []

const files = fs.readdirSync(path.join(process.cwd(), '/pages/route1/'))

files.forEach((file) => {
  pages.push(require(path.join(process.cwd(), '/pages/route1/', file)))
})

return pages

Johan
  • 2,088
  • 2
  • 9
  • 37