Skip to content

Commit

Permalink
fix: Respect user-defined prefix/suffix when looking for default NS (#…
Browse files Browse the repository at this point in the history
…1248)

* fix: Respect user-defined prefix/suffix when looking for default NS

* Add test

Co-authored-by: Isaac Hinman <[email protected]>
  • Loading branch information
alexmchardy and isaachinman authored Jul 13, 2021
1 parent 5391401 commit 315531a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
22 changes: 19 additions & 3 deletions src/config/createConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,15 +116,31 @@ describe('createConfig', () => {
})
})

describe('when filesystem is missing defaultNS', () => {
it('throws an error', () => {
describe('defaultNS validation', () => {
it('when filesystem is missing defaultNS throws an error', () => {
(fs.existsSync as jest.Mock).mockReturnValueOnce(false)

const config = createConfig.bind(null, {
lng: 'en',
} as any)
} as UserConfig)

expect(config).toThrow('Default namespace not found at public/locales/en/common.json')
})

it('uses user provided prefix/suffix with localeStructure', () => {
(fs.existsSync as jest.Mock).mockReturnValueOnce(false)

const config = createConfig.bind(null, {
interpolation: {
prefix: '^^',
suffix: '$$',
},
lng: 'en',
localeStructure: '^^lng$$/^^ns$$',
} as UserConfig)

expect(config).toThrow('Default namespace not found at public/locales/en/common.json')
expect(fs.existsSync).toHaveBeenCalledWith('public/locales/en/common.json')
})
})

Expand Down
4 changes: 3 additions & 1 deletion src/config/createConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ export const createConfig = (userConfig: UserConfig): InternalConfig => {
// https://github.com/isaachinman/next-i18next/issues/358
//
if (typeof defaultNS === 'string' && typeof lng !== 'undefined') {
const defaultLocaleStructure = localeStructure.replace('{{lng}}', lng).replace('{{ns}}', defaultNS)
const prefix = userConfig?.interpolation?.prefix ?? '{{'
const suffix = userConfig?.interpolation?.suffix ?? '}}'
const defaultLocaleStructure = localeStructure.replace(`${prefix}lng${suffix}`, lng).replace(`${prefix}ns${suffix}`, defaultNS)
const defaultFile = `/${defaultLocaleStructure}.${localeExtension}`
const defaultNSPath = path.join(localePath, defaultFile)
const defaultNSExists = fs.existsSync(defaultNSPath)
Expand Down

1 comment on commit 315531a

@vercel
Copy link

@vercel vercel bot commented on 315531a Jul 13, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.