跳至主要内容

[nextjs] 開發筆記

參考文件

i18n 設定

// next.config.js
module.exports = {
i18n: {
locales: ['en-US', 'fr', 'nl-NL'],
defaultLocale: 'en-US',
domains: [
{
domain: 'example.com',
defaultLocale: 'en-US',
},
{
domain: 'example.nl',
defaultLocale: 'nl-NL',
},
{
domain: 'example.fr',
defaultLocale: 'fr',
},
],
},
};

alias absolute import

問題解決

Issues with ES2018 unicode RegExp

通常會出現像這樣的錯誤訊息:

  • e.charCodeAt is not a function at Array.map

Screen Shot 2021-05-06 at 2.19.05 PM

這主要是由於使用了 ES2018 才支援的 unicode RegExp 導致,此時需要安裝 @babel/plugin-transform-unicode-regex 來解決。

$ npm install --save-dev @babel/plugin-transform-unicode-regex

在 Babel 的設定檔中加上此 plugin:

const plugins = [
'@babel/plugin-transform-unicode-regex'
];
備註

此問題在升級到 next@10.2.0 時發生 @ 2021-05-06

ReactDOMServer does not yet support Suspense X next-i18next

問題描述

  • ReactDOMServer does not yet support Suspense

ReactDOMServer does not yet support Suspense

發生情況(需同時成立):

  1. 直接在該頁面重新整理時,使用按鈕或連結 navigate 過去無效
  2. 當使用 next-i18next 時,若在 useTranslation() 的參數中使用了不存在的字典檔,例如:
// foobar 是不存在的字典檔
const { t } = useTranslation('foobar');
備註

這個錯誤和 styled-components 無關,而是和 react-i18next 有關。

解決方式

其中一種解決方式是在 next-i18next.config.js 中加上 useSuspense: false 的設定。像是這樣:

module.exports = {
i18n: {
defaultLocale: 'zh_TW',
locales: ['en', 'zh_TW'],
ns: ['landing'],
},
react: {
useSuspense: false,
},
};

此外,在 18next 官網的 API 文件 中有提到:

warning

In case of react-i18next make sure useSuspense is enabled or handle the ready state in HOCs or hooks yourself.

Styled Components X next.js

問題描述

  • react-dom.development.js?61bb:67 Warning: Prop `className` did not match. Server: "sc-hKFxyN eOWkBO" Client: "sc-gtsrHT loeGDC"

Screen Shot 2021-05-13 at 11.07.31 AM

解決方式

Warning: Prop className did not match. #7322 @ Github Issues

recoil x Next.js

問題描述

  • Duplicate atom key "counterState". This is a FATAL ERROR in production. But it is safe to ignore this warning if it occurred because of hot module replacement.

相關討論

React Context X next.js

  • 從 CSR 切換到 SSR / SSG 時(或反過來),所有的 state 會被清空。

ModuleNotFoundError: Module not found: Error: Can't resolve

問題描述

執行 npm run build 時,有時會找不到某些頁面:

Screen Shot 2021-05-13 at 10.45.49 PM

可能原因

有可能是因為在 .babelrc 中透過 babel-plugin-module-resolver 設定了 alias absolute import,又在 tsconfig.json 中設定。

可能的解法

.babelrc 中,在 plugin 選項中關於 babel-plugin-module-resolver 的設定移除。