【问题标题】:getServerSideProps breaks routing in NextJS/CapacitorgetServerSideProps 中断 NextJS/Capacitor 中的路由
【发布时间】:2022-08-24 00:18:23
【问题描述】:

在使用 nextjs 构建时,我使用以下方法来避免导出 getServerSideProps:

export const getServerSideProps = process.env.SKIP_SSR ? undefined : async (ctx) => { ... }

我用:

\"build:ios\": \"SKIP_SSR=1 next build && SKIP_SSR=1 next export && npx cap copy ios\",

这非常有效,只是当导出并作为 iOS 应用程序运行时,导航不起作用。

为了让它尽可能简单,我在 pages/index.tsx 中添加了这个:

  if(!route.asPath.startsWith(\'/p/home\'))
    route.push(\'/p/home\')
  return (
    <div className={styles.container}>
      I am here in the root page {window.location.href}
    </div>
  )

正在输出:\“我在根页面电容器://localhost/p/home\”

我想看到渲染的页面实际上是在 /p/home/index.tsx 但渲染的是页面/索引。

我发现这是 getServerSideProps 的原因,尽管我以某种方式跳过了 ssr,但它正在构建并破坏 Capacitor 中的路由。

如果我注释掉 getServerSideProps 它运行良好。

有没有办法在构建时正确删除 getServerSideProps?

    标签: reactjs routes next.js capacitor


    【解决方案1】:

    我遇到了同样的问题,并使用 webpack 插件preprocessor-loader 解决了它。

    1. webpack-preprocessor-loader 安装到 devDepencies
      $ yarn add -D webpack-preprocessor-loader
      
      1. 设置 webpack 配置
      // next.config.js
      
      module.exports = {
        webpack: (config) => {
          config.module.rules.push({
            test: /\.tsx$/,
            use: [
              {
                loader: 'webpack-preprocessor-loader',
                options: {
                  params: {
                    // handle this bool parameter via env 
                    isWeb: process.env.IS_WEB,
                  },
                },
              },
            ],
          })
      
          return config
        }
      }
      
      1. 在getServerSideProps周围写#!if#!endif评论
      // yourpage.tsx
      
      import { GetServerSidePropsContext, InferGetServerSidePropsType, NextPage } from 'next'
      
      type PropsType = InferGetServerSidePropsType<typeof getServerSideProps> | undefined
      const Page: NextPage<PropsType> = (props) => { /* your page component */ }
      
      // #!if isWeb
      export const getServerSideProps = async (context) => {
        return {
           props: yourProps
        }
      }
      // #!endif
      
      export default Page
      
      
      1. 根据构建的目标设置环境变量并执行构建。
      // package.json
      {
        "scripts": {
          "build": "IS_WEB=true next build",
          "build:native": "next build && next export && cp -R ./public/* ./out"
        }
      }
      

    【讨论】:

      猜你喜欢
      • 2020-07-28
      • 2020-06-03
      • 2020-07-25
      • 2021-07-15
      • 1970-01-01
      • 2021-11-10
      • 2021-05-12
      • 2020-12-19
      • 2020-10-30
      相关资源
      最近更新 更多