|
1 | 1 | const { parse } = require('dot-properties') |
2 | 2 | const loaderUtils = require('loader-utils') |
3 | 3 | const MessageFormat = require('messageformat') |
| 4 | +const path = require('path') |
| 5 | + |
| 6 | +// expected to follow the pattern baseName_language[_script]_country_variant.properties |
| 7 | +// source: https://docs.oracle.com/javase/9/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-java.util.Locale-java.lang.ClassLoader- |
| 8 | +function localeFromResourcePath (resourcePath, pathSep, defaultLocale) { |
| 9 | + const parts = path.basename(resourcePath).split(pathSep) |
| 10 | + const locale = parts[1] && parts[1].replace(/\..*$/, '').toLowerCase() |
| 11 | + if (locale === 'pt-pt' || (locale === 'pt' && /^pt/i.test(parts[2]))) { |
| 12 | + // European Portuguese is the only locale for which subtags matter |
| 13 | + return 'pt-PT' |
| 14 | + } |
| 15 | + return /^[a-z]{2,3}$/.test(locale || '') ? locale : defaultLocale |
| 16 | +} |
4 | 17 |
|
5 | 18 | module.exports = function (input) { |
6 | | - let { biDiSupport, locales, path } = loaderUtils.getOptions(this) |
7 | | - const translations = parse(input, path || false) |
8 | | - const mf = new MessageFormat(locales) |
| 19 | + const { biDiSupport, defaultLocale, keyPath, pathSep } = loaderUtils.getOptions(this) |
| 20 | + const translations = parse(input, keyPath || false) |
| 21 | + const locale = localeFromResourcePath(this.resourcePath, pathSep || '_', defaultLocale || 'en') |
| 22 | + const mf = new MessageFormat(locale) |
9 | 23 | if (biDiSupport) mf.setBiDiSupport() |
10 | 24 | return mf.compile(translations).toString('module.exports') |
11 | 25 | } |
0 commit comments