/
es2015_translate_plugin.ts
41 lines (40 loc) 路 1.75 KB
/
es2015_translate_plugin.ts
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
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {傻ParsedTranslation} from '@angular/localize';
import {NodePath, PluginObj} from '@babel/core';
import {TaggedTemplateExpression} from '@babel/types';
import {Diagnostics} from '../../diagnostics';
import {TranslatePluginOptions, buildLocalizeReplacement, isBabelParseError, isLocalize, translate, unwrapMessagePartsFromTemplateLiteral} from './source_file_utils';
export function makeEs2015TranslatePlugin(
diagnostics: Diagnostics, translations: Record<string, 傻ParsedTranslation>,
{missingTranslation = 'error', localizeName = '$localize'}: TranslatePluginOptions = {}):
PluginObj {
return {
visitor: {
TaggedTemplateExpression(path: NodePath<TaggedTemplateExpression>) {
try {
const tag = path.get('tag');
if (isLocalize(tag, localizeName)) {
const messageParts = unwrapMessagePartsFromTemplateLiteral(path.node.quasi.quasis);
const translated = translate(
diagnostics, translations, messageParts, path.node.quasi.expressions,
missingTranslation);
path.replaceWith(buildLocalizeReplacement(translated[0], translated[1]));
}
} catch (e) {
if (isBabelParseError(e)) {
// If we get a BabelParseError here then something went wrong with Babel itself
// since there must be something wrong with the structure of the AST generated
// by Babel parsing a TaggedTemplateExpression.
throw path.hub.file.buildCodeFrameError(e.node, e.message);
}
}
}
}
};
}