1 | const _ = require('lodash');
|
2 | const { createFilter } = require('rollup-pluginutils');
|
3 |
|
4 | const filterText = (text) => {
|
5 | if (text) {
|
6 | const filtered = text
|
7 | .toString()
|
8 | .replace(/ \n/g, ' ')
|
9 | .replace(/ /g, ' ')
|
10 | .replace(/\{(\s?\d\s?)\}/g, '{{t$1}}');
|
11 | return filtered;
|
12 | }
|
13 | return text;
|
14 | };
|
15 |
|
16 | module.exports = (opts = {}) => {
|
17 | const include = opts.include || '**/Messages_*.xml';
|
18 | const { exclude } = opts;
|
19 | const filter = createFilter(include, exclude);
|
20 | const filtering = opts.filtering !== false;
|
21 | return {
|
22 | name: 'translation-xml-import',
|
23 | transform(code, id) {
|
24 | if (filtering && !filter(id)) return null;
|
25 | const reg = /<translation\s+id="([\w-]+?)"\s*(qtlid="([0-9]+)")?\s*(?:translate="none")?\s*?>((?:.|\n|\r)*?)<\/translation>/gi;
|
26 | const translations = {};
|
27 | let match;
|
28 | while (match = reg.exec(code)) {
|
29 | _.set(translations, _.get(match, 1), _.get(match, 4, ''));
|
30 | }
|
31 | return {
|
32 | code: `export default ${JSON.stringify(_.mapValues(translations, filterText))};`,
|
33 | map: null,
|
34 | };
|
35 | },
|
36 | };
|
37 | };
|