FoundKey/webpack/module/rules/i18n.ts

50 lines
1,005 B
TypeScript
Raw Normal View History

2017-05-16 15:00:56 +00:00
/**
* Replace i18n texts
*/
const StringReplacePlugin = require('string-replace-webpack-plugin');
2017-10-25 11:29:14 +00:00
export default (lang, locale) => {
function get(key: string) {
let text = locale;
// Check the key existance
const error = key.split('.').some(k => {
if (text.hasOwnProperty(k)) {
text = text[k];
return false;
} else {
return true;
}
});
if (error) {
console.warn(`key '${key}' not found in '${lang}'`);
return key; // Fallback
} else {
return text;
}
}
return {
enforce: 'pre',
test: /\.(tag|js)$/,
exclude: /node_modules/,
loader: StringReplacePlugin.replace({
replacements: [{
pattern: /"%i18n:(.+?)%"/g, replacement: (_, key) => {
return '"' + get(key).replace(/"/g, '\\"') + '"';
}
}, {
pattern: /'%i18n:(.+?)%'/g, replacement: (_, key) => {
return '\'' + get(key).replace(/'/g, '\\\'') + '\'';
}
}, {
2017-05-16 15:00:56 +00:00
pattern: /%i18n:(.+?)%/g, replacement: (_, key) => {
2017-10-25 11:29:14 +00:00
return get(key);
2017-05-16 15:00:56 +00:00
}
2017-10-25 11:29:14 +00:00
}]
})
};
};