npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

next-page-map

v1.0.1

Published

Get a mapping of pathnames to filenames from a Next.js pages directory

Downloads

455

Readme

next-page-map

Get a mapping of files to page paths from your Next.js pages directory.

Installation

npm i next-page-map

Usage

This can be used to build navigation trees and construct links to edit the current page on GitHub. It walks the pages directory synchronously, so it's best placed in your next.config.js and the result passed via publicRuntimeConfig:

const getPageMap = require('next-page-map')
const pageMap = getPageMap()

module.exports = {
  publicRuntimeConfig: {pageMap},
  // the rest of your config
}

Options

The getPageMap() default export takes an optional object of options:

| Key | Description | Default | | :-- | :--- | :--- | | dir | the directory from which to resolve pages | the current working directory (process.cwd()) | | pageExtensions | an optional array of filename extensions to match | ['js', 'jsx'] | | nested | a boolean to enable the nested object format | false |

Map format

The default return format is an object mapping URIs (keys) to filenames (values). Both values have a leading slash, e.g.

/* given the following file structure:
   pages
   ├── about
   │   ├── index.js
   │   ├── mission.js
   │   └── team.js
   ├── index.js
   └── news.js
*/

console.log(JSON.stringify(getPageMap(), null, 2))

/* outputs:
{
  "/": "/index.js",
  "/about": "/about/index.js",
  "/about/mission": "/about/mission.js",
  "/about/team": "/about/team.js",
  "/news": "/news.js"
}
*/

Nested format

If you'd like to build nested navigation from the page map, you can pass nested: true in the options object, which causes getPageMap() to return a recursive structure with the form:

{
  file: '/path/to/foo/index.js',  // the file name relative to <cwd>/pages
  path: '/path/to/foo',           // the URI (path minus page extension and trailing "/index")
  isIndex: true,                  // whether the file w/o extention ends in "/index"
  parent: '/path/to',             // the path of the "parent" page
  children: [<pages>]             // an array of objects whose `.parent` === this.path
}

Examples

Edit links

The map format can be used to look up the filename from any component that uses Next's router, including App components:

// pages/_app.js
import App, {Container} from 'next/app'
import getConfig from 'next/config'
const {pageMap} = getConfig().publicRuntimeConfig

// TODO: replace "<owner>" and "<repo>" with your repo's slugs,
// and replace "master" if that's not your default branch
const editBaseURL = 'https://github.com/<owner>/<repo>/edit/master/pages'
const editURL = filename => `${editBaseURL}${filename}`

export default class extends App {
  render() {
    const {pathname} = this.props.router
    const filename = pageMap[pathname]
    return (
      <Container>
        {/* render your stuff */}
        {filename && (
          <p>
            <a href={editURL(filename)}>Edit this page on GitHub</a>
          </p>
        )}
      </Container>
    )
  }
}

Nested navigation

This example uses nested format with webpack's require.context to get a handle on the actual components that each page renders, then tries to get the text for the link from its displayName:

// next.config.js
const getPageMap = require('next-page-map')
const pageExtensions = ['js', 'mdx']

module.exports = {
  pageExtensions,
  publicRuntimeConfig: {
    pageExtensions,
    pageMap: getPageMap({pageExtensions, nested: true})
  }
  // ...
}
// src/Nav.js
import getConfig from 'next/config'
import NextLink from 'next/link'
import {withRouter} from 'next/router'

const {pageExtensions, pageMap} = getConfig().publicRuntimeConfig

const pattern = new RegExp(`\.(${pageExtensions.join('|')}$`)
const requirePage = require.context('../pages', true, pattern)

export default function Nav(props) {
  return (
    <nav {...props}>
      <NavList links={pageMap} />
    </nav>
  )
}

const NavList = ({links, ...rest}) => (
  <ul {...rest}>
    {links.map(link => (
      <li>
        <NavLink link={page} />
      </li>
    ))}
  </ul>
)

// Note: the withRouter() HOC gives this component a `router` prop,
// which memorializes the `pathname` of the current page
const NavLink = withRouter(({link, router, ...rest}) => {
  const {file, path, children} = link
  const current = router.pathname === path
  
  // require.context().keys() returns all of the matched filenames,
  // but they're relative to the '../pages' path, so the only real
  // difference is the leading "."
  const contextPath = requirePage.keys().find(key => key === `.${file}`)
  
  let text = file
  if (contextPath) {
    const Page = requirePage(contextPath)
    text = Page.displayName || Page.name || text
  }
  return (
    <NextLink to={path}>
      <a href={path} aria-current={current} {...rest}>{text}</a>
    </NextLink>
  )
})