diff --git a/packages/react-intl-universal/src/ReactIntlUniversal.js b/packages/react-intl-universal/src/ReactIntlUniversal.js index 0c6444a..38582cd 100644 --- a/packages/react-intl-universal/src/ReactIntlUniversal.js +++ b/packages/react-intl-universal/src/ReactIntlUniversal.js @@ -84,8 +84,14 @@ class ReactIntlUniversal { } try { - const msgFormatter = new IntlMessageFormat(msg, currentLocale, formats); - return msgFormatter.format(variables); + const cacheKey = key + JSON.stringify(variables) + currentLocale; + let computedValue = this.cache[cacheKey]; + if (typeof computedValue === 'undefined') { + const msgFormatter = new IntlMessageFormat(msg, currentLocale, formats); + computedValue = msgFormatter.format(variables); + this.cache[cacheKey] = computedValue; + } + return computedValue; } catch (err) { this.options.warningHandler( `react-intl-universal format message failed for key='${key}'.`, @@ -188,6 +194,8 @@ class ReactIntlUniversal { constants.defaultFormats ); + this.cache = Object.create(null) + return new Promise((resolve, reject) => { // init() will not load external common locale data anymore. // But, it still return a Promise for abckward compatibility. diff --git a/packages/react-intl-universal/test/index.test.js b/packages/react-intl-universal/test/index.test.js index 0a878be..bcc8c96 100644 --- a/packages/react-intl-universal/test/index.test.js +++ b/packages/react-intl-universal/test/index.test.js @@ -368,3 +368,15 @@ test("Resolve directly if the environment is not browser", async () => { }); expect(result).toBe(undefined); }); + +test("cache", () => { + const key = "HELLO"; + const variables = { name: 'World' }; + const currentLocale = "en-US" + const cacheKey = key + JSON.stringify(variables) + currentLocale; + + intl.init({ locales, currentLocale }); + + expect(intl.get(key, variables)).toBe("Hello, World"); + expect(intl.cache[cacheKey]).toBe("Hello, World"); +}); \ No newline at end of file