首页 > 解决方案 > Intl Polyfill + Next.js SSR 应用程序

问题描述

如何在 Next.js 应用程序上填充 intl?有的中文浏览器还没有,我们用react-intl,需要Intl。

标签: webpacknext.jsserver-side-renderingreact-intl

解决方案


Next.js 中的 polyfills(一般)

Next.js 通常有一些 polyfill 示例:
https ://github.com/vercel/next.js/tree/canary/examples/with-polyfills

Next.js 建议在<App>组件内部或使用 polyfill 的单个组件中导入所需的 polyfill。

例如:

// /pages/_app.js

import 'polyfill_some_feature';

function MyApp({ Component, pageProps }){
  return <Component { ...pageProps } />
}

export default MyApp

用于IntlAPI的 polyfill

formatjs / react-intl为API提供了一些polyfillsIntl

您需要的功能,如Intl.getCanonicalLocales, Intl.Locale, Intl.PluralRules, ... 必须单独导入。

请注意,polyfill 相互依赖,因此调用它们的顺序很重要。
例如 polyfill 用于Intl.getCanonicalLocales检查 if typeof Intl === 'undefined',但 polyfillIntl.Locale依赖于Intl已经存在。

这是他们的一个例子(这个例子是为了实现getCanonicalLocales):
https ://formatjs.io/docs/polyfills/intl-getcanonicallocales/#dynamic-import--capability-detection

npm i @formatjs/intl-getcanonicallocales
import { shouldPolyfill } from '@formatjs/intl-getcanonicallocales/should-polyfill';

async function polyfill() {
  if( shouldPolyfill() ){
    await import('@formatjs/intl-getcanonicallocales/polyfill');
  }
}

推荐阅读