NextJS:仅开发页面

NextJS: dev only pages

我想创建一个 /storybook 页面。但此页面仅用于开发目的。我的意思是,我不希望在生产模式下可以访问此页面。

我们怎样才能做到这一点?

我不确定最好的方法是什么。我认为你有几种方法。

和Next.js9.5+

您可以使用 rewrite 来确保到 /storybook 的流量会转到您的 404 页面。

// next.config.js
// more configs
  async rewrites() {
    return [
      {
        source: '/storybook',
        destination: process.env.NODE_ENV === 'production' ? '/404' : '/storybook',
      }
    ];
  },
// more configs

和Next.js10+

您可以在 getServerSidePropsgetStaticProps 中使用 notFound 属性。有关详细信息,您可以找到 doc here

// or getServerSideProps
export function getStaticProps() {
  return {
    // returns the default 404 page with a status code of 404 in production
     notFound: process.env.NODE_ENV === 'production'
  }
}

使用自定义服务器

取决于服务器框架,您可以在那里重定向到 404。