turbopack_ecmascript/references/
constant_value.rs

1use anyhow::Result;
2use serde::{Deserialize, Serialize};
3use swc_core::quote;
4use turbo_tasks::{NonLocalValue, Value, Vc, debug::ValueDebugFormat, trace::TraceRawVcs};
5use turbopack_core::{
6    chunk::ChunkingContext, compile_time_info::CompileTimeDefineValue, module_graph::ModuleGraph,
7};
8
9use super::AstPath;
10use crate::{
11    code_gen::{CodeGen, CodeGeneration},
12    create_visitor,
13};
14
15#[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
16pub struct ConstantValueCodeGen {
17    value: CompileTimeDefineValue,
18    path: AstPath,
19}
20
21impl ConstantValueCodeGen {
22    pub fn new(value: Value<CompileTimeDefineValue>, path: AstPath) -> Self {
23        ConstantValueCodeGen {
24            value: value.into_value(),
25            path,
26        }
27    }
28    pub async fn code_generation(
29        &self,
30        _module_graph: Vc<ModuleGraph>,
31        _chunking_context: Vc<Box<dyn ChunkingContext>>,
32    ) -> Result<CodeGeneration> {
33        let value = self.value.clone();
34
35        let visitor = create_visitor!(self.path, visit_mut_expr(expr: &mut Expr) {
36            *expr = match value {
37                CompileTimeDefineValue::Bool(true) => quote!("(\"TURBOPACK compile-time value\", true)" as Expr),
38                CompileTimeDefineValue::Bool(false) => quote!("(\"TURBOPACK compile-time value\", false)" as Expr),
39                CompileTimeDefineValue::String(ref s) => quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = s.to_string().into()),
40                CompileTimeDefineValue::JSON(ref s) => quote!("(\"TURBOPACK compile-time value\", JSON.parse($e))" as Expr, e: Expr = s.to_string().into()),
41            };
42        });
43
44        Ok(CodeGeneration::visitors(vec![visitor]))
45    }
46}
47
48impl From<ConstantValueCodeGen> for CodeGen {
49    fn from(val: ConstantValueCodeGen) -> Self {
50        CodeGen::ConstantValueCodeGen(val)
51    }
52}