File size: 1,779 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const i18nImports = new Set( [ '__', '_n', '_nx', '_x' ] );

module.exports = function ( babel ) {
	const { types: t } = babel;

	// Collects named imports from the "@wordpress/i18n" package
	function collectAllImportsAndAliasThem( path ) {
		const node = path.node;
		const aliases = [];
		if ( t.isStringLiteral( node.source ) && node.source.value === '@wordpress/i18n' ) {
			const specifiers = path.get( 'specifiers' );

			for ( const specifier of specifiers ) {
				if ( t.isImportSpecifier( specifier ) ) {
					const importedNode = specifier.node.imported;
					const localNode = specifier.node.local;

					if ( t.isIdentifier( importedNode ) && t.isIdentifier( localNode ) ) {
						if ( i18nImports.has( importedNode.name ) ) {
							aliases.push( {
								original: localNode.name,
								aliased: 'alias' + localNode.name,
							} );
							specifier.replaceWith(
								t.importSpecifier(
									t.identifier( 'alias' + localNode.name ),
									t.identifier( importedNode.name )
								)
							);
							path.scope.removeBinding( localNode.name );
						}
					}
				}
			}
			path.scope.registerDeclaration( path );
		}
		return aliases;
	}

	return {
		name: 'babel-plugin-preserve-i18n',
		visitor: {
			ImportDeclaration( path ) {
				const aliases = collectAllImportsAndAliasThem( path );
				if ( aliases.length > 0 ) {
					const declarations = aliases.map( ( { original, aliased } ) =>
						t.variableDeclarator( t.identifier( original ), t.identifier( aliased ) )
					);
					const aliasDeclarationNode = t.variableDeclaration( 'const', declarations );
					path.insertAfter( aliasDeclarationNode );

					const aliasDeclarationPath = path.getNextSibling();
					path.scope.registerDeclaration( aliasDeclarationPath );
				}
			},
		},
	};
};