forked from akameco/extract-react-intl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (79 loc) · 2.67 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// @flow weak
'use strict'
const path = require('path')
const glob = require('glob')
const pify = require('pify')
const merge = require('lodash.merge')
const mergeWith = require('lodash.mergewith')
const { resolvePlugin, resolvePreset, transformFile } = require('@babel/core')
const readBabelrcUp = require('read-babelrc-up')
const localeMap = arr =>
arr.reduce((obj, x) => {
obj[x] = {}
return obj
}, {})
const concatArray = (obj, src) => {
if (Array.isArray(obj)) {
return obj.concat(src)
}
return undefined
}
const createResolveList = fn => (list, cwd) =>
list.map(x => (typeof x === 'string' ? fn(x, cwd) : x))
const resolvePresets = createResolveList(resolvePreset)
const resolvePlugins = createResolveList(resolvePlugin)
const getBabelrc = cwd => {
try {
const babelrc = readBabelrcUp.sync({ cwd }).babel
if (!babelrc.env) {
return babelrc
}
const env = process.env.BABEL_ENV || process.env.NODE_ENV || 'development'
return mergeWith(babelrc, babelrc.env[env], concatArray)
} catch (error) {
return { presets: [], plugins: [] }
}
}
const getBabelrcDir = cwd => path.dirname(readBabelrcUp.sync({ cwd }).path)
module.exports = async (locales, pattern, opts) => {
if (!Array.isArray(locales)) {
throw new TypeError(`Expected a Array, got ${typeof locales}`)
}
if (typeof pattern !== 'string') {
throw new TypeError(`Expected a string, got ${typeof pattern}`)
}
opts = {
cwd: process.cwd(),
defaultLocale: 'en',
...opts
}
const babelrc = opts.babelConfig || getBabelrc(opts.cwd) || {}
const babelrcDir = opts.babelConfig ? opts.cwd : getBabelrcDir(opts.cwd)
const { moduleSourceName } = opts
const pluginOptions = moduleSourceName ? { moduleSourceName } : {}
const { presets = [], plugins = [] } = babelrc
// eslint-disable-next-line global-require
presets.unshift({
plugins: [[require('babel-plugin-react-intl').default, pluginOptions]]
})
const extractFromFile = async file => {
const { metadata: result } = await pify(transformFile)(file, {
presets: resolvePresets(presets, babelrcDir),
plugins: resolvePlugins(plugins, babelrcDir)
})
const localeObj = localeMap(locales)
for (const { id, defaultMessage } of result['react-intl'].messages) {
for (const locale of locales) {
localeObj[locale][id] =
opts.defaultLocale === locale ? defaultMessage : ''
}
}
return localeObj
}
const files = await pify(glob)(pattern)
if (files.length === 0) {
throw new Error(`File not found (${pattern})`)
}
const arr = await Promise.all(files.map(extractFromFile))
return arr.reduce((h, obj) => merge(h, obj), localeMap(locales))
}