From fb5e8d15a0db74350fe659d4a3b56fb2401b70aa Mon Sep 17 00:00:00 2001 From: Mark Skelton Date: Thu, 28 Jul 2022 09:29:57 -0500 Subject: [PATCH] Support default exports. (#8) --- .changeset/small-comics-rush.md | 5 +++++ src/index.ts | 8 ++++++-- test/AsyncBackend.spec.ts | 8 ++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 .changeset/small-comics-rush.md diff --git a/.changeset/small-comics-rush.md b/.changeset/small-comics-rush.md new file mode 100644 index 0000000..dd5f524 --- /dev/null +++ b/.changeset/small-comics-rush.md @@ -0,0 +1,5 @@ +--- +'i18next-async-backend': patch +--- + +Support ESModule default exports. diff --git a/src/index.ts b/src/index.ts index d2d36e9..c3e06e0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,10 @@ import { BackendModule, ReadCallback, Services } from 'i18next' -type ResourceFetcher = () => Promise> +type ResourceFetcher = () => Promise<{ + __esModule?: true + default?: Record + [key: string]: unknown +}> export interface AsyncBackendOptions { resources?: { @@ -31,7 +35,7 @@ export default class AsyncBackend if (resourceFetcher) { resourceFetcher() - .then((resource) => callback(null, resource)) + .then((res) => callback(null, res.__esModule ? res.default : res)) .catch((err) => callback(err, false)) } else { callback(new Error('resource not found'), false) diff --git a/test/AsyncBackend.spec.ts b/test/AsyncBackend.spec.ts index 2585282..e161a3e 100644 --- a/test/AsyncBackend.spec.ts +++ b/test/AsyncBackend.spec.ts @@ -58,3 +58,11 @@ it('should load multiple languages', async () => { expect(t('ns1:fruit')).toBe('Manzanas') expect(t('ns2:fruit')).toBe('Naranjas') }) + +it('should parse ESM default exports', async () => { + const { t } = await init(['translation'], { + en: () => Promise.resolve({ __esModule: true, default: { foo: 'bar' } }), + }) + + expect(t('foo')).toBe('bar') +})