Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Remove serialize-javascript and add configOverride to appWithTranslation #972

Merged
merged 4 commits into from
Feb 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,10 @@ Note: `useTranslation` provides namespaces to the component that you use it in.

### 5. Advanced configuration

If you need to modify more advanced configuration options, you can add a `next-i18next.config.js` file to the root of your project. That file should have a default export. For example:

#### Passing other config options

If you need to modify more advanced configuration options, you can pass them via `next-i18next.config.js`. For example:

```js
const path = require('path')
Expand All @@ -154,6 +157,28 @@ module.exports = {
}
```

#### Unserialisable configs

Some `i18next` plugins (which you can pass into `config.use`) are unserialisable, as they contain functions and other JavaScript primitives.

You may run into this if your use case is more advanced. You'll see NextJs throw an error like:

```
Error: Error serializing `._nextI18Next.userConfig.use[0].process` returned from `getStaticProps` in "/my-page".
Reason: `function` cannot be serialized as JSON. Please only return JSON serializable data types.
```

To fix this, you'll need to set `config.serializeConfig` to `false`, and manually pass your config into `appWithTranslation`:

```tsx
import { appWithTranslation } from 'next-i18next'
import nextI18NextConfig from '../next-i18next.config.js'

const MyApp = ({ Component, pageProps }) => <Component {...pageProps} />

export default appWithTranslation(MyApp, nextI18NextConfig)
```

#### Options

| Key | Default value |
Expand Down
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,7 @@
"hoist-non-react-statics": "^3.2.0",
"i18next": "^19.8.4",
"i18next-fs-backend": "^1.0.7",
"react-i18next": "^11.8.8",
"serialize-javascript": "^5.0.1"
"react-i18next": "^11.8.8"
},
"peerDependencies": {
"next": ">= 9.5.0",
Expand Down
40 changes: 40 additions & 0 deletions src/appWithTranslation.client.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const renderComponent = () =>
pageProps={{
_nextI18Next: {
initialLocale: 'en',
userConfig: {},
},
}}
/>
Expand All @@ -48,6 +49,45 @@ describe('appWithTranslation', () => {
expect(screen.getByText('Hello world')).toBeTruthy()
})

it('respects configOverride', () => {
const DummyAppConfigOverride = appWithTranslation(() => (
<div>Hello world</div>
), {
configOverride: 'custom-value',
isaachinman marked this conversation as resolved.
Show resolved Hide resolved
} as any)
render(
<DummyAppConfigOverride
pageProps={{
_nextI18Next: {
initialLocale: 'en',
},
}}
/>
)
const [args] = (I18nextProvider as jest.Mock).mock.calls

expect(screen.getByText('Hello world')).toBeTruthy()
expect(args[0].i18n.options.configOverride).toBe('custom-value')
})

it('throws an error if userConfig and configOverride are both missing', () => {
const DummyAppConfigOverride = appWithTranslation(() => (
<div>Hello world</div>
))
expect(
() => render(
<DummyAppConfigOverride
pageProps={{
_nextI18Next: {
initialLocale: 'en',
userConfig: null,
},
}}
/>
)
).toThrow('appWithTranslation was called without a next-i18next config')
})

it('returns an I18nextProvider', () => {
renderComponent()
expect(I18nextProvider).toHaveBeenCalledTimes(1)
Expand Down
23 changes: 14 additions & 9 deletions src/appWithTranslation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { I18nextProvider } from 'react-i18next'
import { createConfig } from './config/createConfig'
import createClient from './createClient'

import { SSRConfig } from '../types'
import { SSRConfig, UserConfig } from '../types'

export { I18nContext, Trans, useTranslation, withTranslation } from 'react-i18next'

Expand All @@ -14,26 +14,31 @@ type AppProps = {
}

export const appWithTranslation = <P extends Record<string, unknown>>(
WrappedComponent: React.ComponentType | React.ElementType):
WrappedComponent: React.ComponentType | React.ElementType,
configOverride: UserConfig = null,
):
React.ComponentType<P> | React.ElementType<P> => {
const AppWithTranslation = (props: AppProps) => {
let i18n = null
let locale = null

if (props?.pageProps?._nextI18Next) {
const {
initialI18nStore,
initialLocale,
userConfig,
} = props.pageProps._nextI18Next
let { userConfig } = props.pageProps._nextI18Next
const { initialI18nStore, initialLocale } = props.pageProps._nextI18Next

const parsedUserConfig = Function(`'use strict';return(${userConfig})`)()
if (userConfig === null && configOverride === null) {
throw new Error('appWithTranslation was called without a next-i18next config')
}

if (configOverride !== null) {
userConfig = configOverride
}

locale = initialLocale;

({ i18n } = createClient({
...createConfig({
...parsedUserConfig,
...userConfig,
lng: initialLocale,
}),
lng: initialLocale,
Expand Down
1 change: 1 addition & 0 deletions src/config/defaultConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export const defaultConfig = {
react: {
useSuspense: true,
},
serializeConfig: true,
strictMode: true,
use: [],
}
3 changes: 1 addition & 2 deletions src/serverSideTranslations.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import fs from 'fs'
import serialize from 'serialize-javascript'
import path from 'path'

import { createConfig } from './config/createConfig'
Expand Down Expand Up @@ -56,7 +55,7 @@ export const serverSideTranslations = async (
_nextI18Next: {
initialI18nStore,
initialLocale,
userConfig: userConfig !== null ? serialize(userConfig) : null,
userConfig: config.serializeConfig ? userConfig : null,
},
}
}
113 changes: 0 additions & 113 deletions src/utils/consoleMessage.test.ts

This file was deleted.

85 changes: 0 additions & 85 deletions src/utils/consoleMessage.ts

This file was deleted.

1 change: 0 additions & 1 deletion src/utils/index.ts

This file was deleted.

1 change: 1 addition & 0 deletions types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export type UserConfig = {
localeExtension?: string
localePath?: string
localeStructure?: string
serializeConfig: boolean
strictMode?: boolean
use?: any[]
} & InitOptions
Expand Down
Loading