【问题标题】:NextJS: dev only pagesNextJS:仅开发页面
【发布时间】:2021-02-22 16:43:10
【问题描述】:

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

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

【问题讨论】:

    标签: html next.js hidden


    【解决方案1】:

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

    使用 Next.js 9.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.js 10+

    您可以在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。

    【讨论】:

    • 当您运行 npm run build 时,来自开发页面的导入是否会进入最终构建?
    • 我无法建议对您的答案进行修改,所以我就写在这里:您应该返回{ notFound: true }{ props: {} }。返回{ props: { notFound: true } } 不起作用。
    • @EddyVinck 感谢您的指出。我更新了答案。
    猜你喜欢
    • 2021-01-11
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 2021-09-20
    • 1970-01-01
    • 2021-12-08
    • 2022-09-23
    相关资源
    最近更新 更多