diff --git a/src/composer.ts b/src/composer.ts index 9a309f37d..2bc0deb1b 100644 --- a/src/composer.ts +++ b/src/composer.ts @@ -218,7 +218,7 @@ function getLocaleMessages( return ret } -function addPreCompileMessages( +export function addPreCompileMessages( messages: LocaleMessages, functions: MessageFunctions ): void { @@ -226,7 +226,10 @@ function addPreCompileMessages( keys.forEach(key => { const compiled = functions[key] const { l, k } = JSON.parse(key) - const targetLocaleMessage = (messages[l] = messages[l] || {}) + if (!messages[l]) { + messages[l] = {} + } + const targetLocaleMessage = messages[l] const paths = parsePath(k) if (paths != null) { const len = paths.length @@ -234,14 +237,18 @@ function addPreCompileMessages( let i = 0 while (i < len) { const path = paths[i] - const val = last[path] - if (val != null) { - last[path] = {} + if (i === len - 1) { + last[path] = compiled + break + } else { + let val = last[path] + if (!val) { + last[path] = val = {} + } + last = val + i++ } - last = val - i++ } - last = compiled } }) } diff --git a/test/composer.test.ts b/test/composer.test.ts index 3c4d38cd3..88ea31214 100644 --- a/test/composer.test.ts +++ b/test/composer.test.ts @@ -7,7 +7,12 @@ jest.mock('../src/utils', () => ({ })) import { warn } from '../src/utils' -import { createComposer, MissingHandler } from '../src/composer' +import { + createComposer, + MissingHandler, + addPreCompileMessages +} from '../src/composer' +import { generateFormatCacheKey } from '../src/utils' import { watch } from 'vue' describe('locale', () => { @@ -716,4 +721,26 @@ describe('__i18n', () => { }) }) +test('addPreCompileMessages', () => { + const messages = {} + const functions = Object.create(null) + const msg1 = () => {} + const msg2 = () => {} + functions[generateFormatCacheKey('en', 'hello', 'hello,world')] = msg1 + functions[ + generateFormatCacheKey('ja', 'foo.bar.hello', 'こんにちは、世界') + ] = msg2 + addPreCompileMessages(messages, functions) + expect(messages['en']).toMatchObject({ + hello: msg1 + }) + expect(messages['ja']).toMatchObject({ + foo: { + bar: { + hello: msg2 + } + } + }) +}) + /* eslint-enable @typescript-eslint/no-empty-function */