Skip to content

Commit 9631ff5

Browse files
committed
Parse locale from filename
1 parent 859e582 commit 9631ff5

4 files changed

Lines changed: 19 additions & 7 deletions

File tree

example/src/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import messages from './messages.properties'
1+
import messages from './messages_en.properties'
22
const { format, messages: errors } = messages.errors
33

44
function component() {

example/webpack.config.js

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,7 @@ module.exports = {
1212
test: /\.properties$/,
1313
loader: require.resolve('messageformat-properties-loader'),
1414
options: {
15-
biDiSupport: false,
16-
locales: 'en',
17-
path: true
15+
keyPath: true
1816
}
1917
}
2018
]

index.js

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,25 @@
11
const { parse } = require('dot-properties')
22
const loaderUtils = require('loader-utils')
33
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+
}
417

518
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)
923
if (biDiSupport) mf.setBiDiSupport()
1024
return mf.compile(translations).toString('module.exports')
1125
}

0 commit comments

Comments
 (0)