Skip to content

Commit

Permalink
Use import() to dynamically load languages.
Browse files Browse the repository at this point in the history
  • Loading branch information
goto-bus-stop committed May 25, 2017
1 parent 370fc08 commit e4c831f
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 46 deletions.
37 changes: 11 additions & 26 deletions src/locale.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,21 @@
import i18next from 'i18next';

import cs from '../locale/cs.yaml';
import cy from '../locale/cy.yaml';
import de from '../locale/de.yaml';
import en from '../locale/en.yaml';
import fr from '../locale/fr.yaml';
import ko from '../locale/ko.yaml';
import nl from '../locale/nl.yaml';
import pt from '../locale/pt.yaml';
import zh from '../locale/zh.yaml';

const resources = {
cs,
cy,
de,
en,
fr,
ko,
nl,
pt,
zh
cs: () => import('../locale/cs.yaml'),
cy: () => import('../locale/cy.yaml'),
de: () => import('../locale/de.yaml'),
fr: () => import('../locale/fr.yaml'),
ko: () => import('../locale/ko.yaml'),
nl: () => import('../locale/nl.yaml'),
pt: () => import('../locale/pt.yaml'),
zh: () => import('../locale/zh.yaml')
};

class UwaveBackend {
static type = 'backend';
type = 'backend';
cache = {};
cache = { en: Promise.resolve(en) };

getResource(language) {
if (this.cache[language]) {
Expand All @@ -34,13 +24,8 @@ class UwaveBackend {
if (!resources[language]) {
return Promise.reject(new Error(`The language "${language}" is not supported.`));
}
// Instantly return compiled-in locales.
if (typeof resources[language] === 'object') {
return Promise.resolve(resources[language]);
}

this.cache[language] = fetch(resources[language])
.then(response => response.json());
this.cache[language] = resources[language]();

return this.cache[language];
}
Expand All @@ -66,7 +51,7 @@ i18next.init({
}
});

export const availableLanguages = Object.keys(resources);
export const availableLanguages = ['en', ...Object.keys(resources)];

export default function createLocale(language) {
const locale = i18next.cloneInstance();
Expand Down
8 changes: 0 additions & 8 deletions tasks/utils/minifyJsonLoader.js

This file was deleted.

13 changes: 1 addition & 12 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,20 +176,9 @@ module.exports = {
use: [ 'css-loader', 'postcss-loader' ]
})
},
// Locales: Compile the `en` fallback locale into the bundle.
{
test: /en\.yaml$/,
use: [ 'json-loader', 'yaml-loader' ]
},
// Load other locales dynamically.
{
test: /\.yaml$/,
exclude: /en\.yaml$/,
use: [
{ loader: 'file-loader', query: { name: '[name]_[hash:7].json' } },
nodeEnv === 'production' && require.resolve('./tasks/utils/minifyJsonLoader'),
'yaml-loader'
].filter(Boolean)
use: [ 'json-loader', 'yaml-loader' ]
},
{
test: /\.json$/,
Expand Down

0 comments on commit e4c831f

Please sign in to comment.