How can I polyfill intl on a Next.js application? Some Chinese browsers still don't have it, and we use react-intl, which requires Intl.
2 Answers
polyfills in Next.js (in general)
Next.js has some examples for polyfills in general:
https://github.com/vercel/next.js/tree/canary/examples/with-polyfills
Next.js recommends to import the needed polyfill(s) inside the <App>
component, or in the individual component that uses the polyfill(s).
E.g.:
// /pages/_app.js
import 'polyfill_some_feature';
function MyApp({ Component, pageProps }){
return <Component { ...pageProps } />
}
export default MyApp
polyfills for the Intl
API
formatjs / react-intl provides some polyfills for the Intl
API.
The features that you need, like Intl.getCanonicalLocales
, Intl.Locale
, Intl.PluralRules
, ..., have to be imported seperately.
Note that the polyfills depend on each other, so the order in which they are called matters.
E.g. the polyfill for Intl.getCanonicalLocales
checks if typeof Intl === 'undefined'
, but the polyfill for Intl.Locale
relies on the existence of Intl
already.
Here is one of their examples (this one is for implementing 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');
}
}

- 4,856
- 1
- 20
- 41
You can use a custom express server in order to apply the Intl polyfill.

- 32,615
- 9
- 69
- 88