首页 > 解决方案 > 将数据放在 ServersideProps 上

问题描述

是否可以通过 Next.js 中的 getServersideProps() 从客户端的服务器端配置文件中获取数据?如何将数据放入 props 中?或者如何以其他方式在客户端上获取它?我publicRuntimeConfig在 next.config.js 中尝试过,但它是未定义的,我不知道为什么......

标签: node.jstypescriptnext.js

解决方案


很难确切地说出发生了什么,但我从经验中有一个想法:您需要确保在包含任何使用的模块nextJSApp.prepare() 之前next/config调用。

举个例子,

// SomeComponent.tsx
import { getConfig } from 'next/config'

const config = getConfig()

export interface X { ... }
// server.ts
import { X } from './SomeComponent'

app.prepare().then(...)

这失败了,因为模块首先加载并且配置app.prepare在完成之前尚未初始化。

对此的解决方案是,import(...)如果您只需要一个类型,则使用 TypeScript 的语法,或者require在运行时使用节点的动态解析。


推荐阅读