NextJS:仅限开发页面

问题描述 投票:0回答:2

我想创建一个

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

我们怎样才能实现这一目标?

html next.js hidden
2个回答
13
投票

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

使用 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+

您可以在

notFound
getServerSideProps
中使用
getStaticProps
属性。欲了解更多信息,您可以在这里找到文档

// 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。


0
投票

对于使用 App Router 的 Next.js,我的不完美解决方案是在顶部

layout.tsx
文件中添加一个条件,以便在开发环境外部调用时使用
notFound()
进行响应。

例如: 使用

/(dev)/
文件创建路由器组
layout.tsx
目录,然后将
/storybook
目录移动到其中。

/(dev)/layout.tsx

import React from "react";
import {notFound} from "next/navigation";

export default function DevLayout({children}: {
  children: React.ReactNode
}) {
  if (process.env.NODE_ENV != 'development')
    notFound()
  
  return <>{children}</>
}
© www.soinside.com 2019 - 2024. All rights reserved.