使用静态 HTML 导出的 Next.js 中的客户端初始化

Client-side initialization in Next.js with Static HTML Export

我们正在开发一个 Next.js 应用程序,使用 react-i18next 进行本地化。我们正在使用 next exportStatic HTML Export). The react-i18next library requires initialization code,我不确定在哪里调用它。

(我们没有使用 next-i18next,因为 that does not work with next export。)

现在我在一个单独的模块中进行了初始化(在 pages/ 之外)。如果我将该模块导入 pages/_app.tsx 和 运行 构建脚本 (next build && next export),构建将挂起。当我按下 Ctrl-C 时,我得到:

Error: setRawMode EIO

如果我尝试从 custom Document.

导入它,也会发生同样的事情

我目前的解决方法是在 pages/index.tsx 中导入初始化模块 - 可行,但感觉不对。

该项目使用 TypeScript 和 yarn v1,并使用 create-next-app 搭建了脚手架(以防其中任何一个相关)。

一个Custom App import does appear to be the correct place for client-side initialization code (inferred based on Custom Polyfills).

问题是调用 next build && next export 时将执行 _app 模块。异步调用(在我的例子中是 i18next-http-backend)会导致构建脚本挂起。

修复方法是将初始化代码包装在:

if (typeof window !== 'undefined') {
  // initialization code - will only run on client side
}

基于https://flaviocopes.com/nextjs-server-client-code/

这确实意味着初始化代码也不会 运行 用于 Jest 测试,但是 react-i18next can be mocked.