Skip to main content

intlayer_swc_plugin/
dictionary_entry.rs

1//! Replacement of the generated dictionaries entry module.
2
3use crate::ast::make_ident;
4use swc_core::{
5    common::{SyntaxContext, DUMMY_SP},
6    ecma::ast::*,
7};
8
9/// Name of the named export the entry module exposes alongside its default one.
10const GET_DICTIONARIES_EXPORT_NAME: &str = "getDictionaries";
11
12/// Builds the empty stand-in for the generated dictionaries entry module:
13///
14/// ```js
15/// export default {};
16/// export const getDictionaries = () => ({});
17/// ```
18///
19/// Every `useIntlayer('key')` call has already been rewritten to read from a
20/// direct import, so the global registry the entry module used to hold is dead
21/// weight — emptying it lets the bundler drop every dictionary that is not
22/// actually referenced.
23pub fn build_empty_dictionaries_entry() -> Program {
24    let empty_object = || {
25        Box::new(Expr::Object(ObjectLit {
26            span: DUMMY_SP,
27            props: Vec::new(),
28        }))
29    };
30
31    let default_export = ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(ExportDefaultExpr {
32        span: DUMMY_SP,
33        expr: empty_object(),
34    }));
35
36    let named_export = ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
37        span: DUMMY_SP,
38        decl: Decl::Var(Box::new(VarDecl {
39            span: DUMMY_SP,
40            ctxt: SyntaxContext::empty(),
41            kind: VarDeclKind::Const,
42            declare: false,
43            decls: vec![VarDeclarator {
44                span: DUMMY_SP,
45                name: Pat::Ident(BindingIdent {
46                    id: make_ident(GET_DICTIONARIES_EXPORT_NAME),
47                    type_ann: None,
48                }),
49                init: Some(Box::new(Expr::Arrow(ArrowExpr {
50                    span: DUMMY_SP,
51                    ctxt: SyntaxContext::empty(),
52                    params: vec![],
53                    is_async: false,
54                    is_generator: false,
55                    type_params: None,
56                    return_type: None,
57                    body: Box::new(BlockStmtOrExpr::Expr(empty_object())),
58                }))),
59                definite: false,
60            }],
61        })),
62    }));
63
64    Program::Module(Module {
65        span: DUMMY_SP,
66        body: vec![default_export, named_export],
67        shebang: None,
68    })
69}