【问题标题】:Client-side initialization in Next.js with Static HTML ExportNext.js 中的客户端初始化与静态 HTML 导出
【发布时间】:2021-06-22 15:53:21
【问题描述】:

我们正在开发一个 Next.js 应用,使用 react-i18next 进行本地化。我们正在使用next export (Static HTML Export)。 react-i18next 库需要initialization code,我不知道在哪里调用它。

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

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

错误:setRawMode EIO

如果我尝试从 custom Document 导入它,也会发生同样的事情。

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

该项目使用 TypeScript 和 yarn v1,并使用 create-next-app 搭建脚手架(以防万一)。

【问题讨论】:

    标签: next.js react-i18next static-html


    【解决方案1】:

    Custom App 导入似乎确实是客户端初始化代码的正确位置(根据 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 2020-02-22
      • 2021-04-24
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      相关资源
      最近更新 更多