Unverified Commit 3f177059 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: properly set NODE_ENV for SWC plugins (#92579)

### What?

Closes https://github.com/vercel/next.js/pull/92650
Closes https://github.com/vercel/next.js/issues/92547

When Turbopack runs SWC transform plugins, it passes a `TransformPluginMetadataContext` that includes the current `NODE_ENV`. Previously this value was hardcoded to `"development"` regardless of the actual build mode, causing SWC plugins to misbehave during production builds.

### Why?

`SwcPluginMetadataContext` is used by SWC plugins (e.g. `babel-plugin-styled-components`, `@swc/plugin-emotion`) to conditionally produce development vs. production output — for instance, injecting display names and data attributes only in development. With `NODE_ENV` always set to `"development"`, plugins could never produce their optimised production output, resulting in larger bundles and missing minification in `next build`.

Fixes https://github.com/vercel/next.js/issues/92547

### How?

`NODE_ENV` is now derived from the `process.env.NODE_ENV` compile-time define that is already part of `CompileTimeInfo` (the same source of truth used for dead-code elimination). The resolution happens in `EcmascriptModuleAsset::parse()` via a new shared helper `node_env_from_compile_time_info()` in `parse.rs`, and the value is stored on `TransformContext` so every `CustomTransformer` implementation can read it from `ctx.node_env` without needing access to the broader compilation context.

Key design decisions:

- **`TransformContext`** is the right place: it is the per-file context passed to every `CustomTransformer::transform()` call, so storing `node_env` there follows the existing pattern and avoids coupling the plugin struct to the build mode.
- **Webpack analysis path**: `compile_time_info` is now threaded through `webpack_runtime()`, `module_references()`, and the webpack reference structs (`WebpackModuleAsset`, `WebpackChunkAssetReference`, `WebpackEntryAssetReference`, `WebpackRuntimeAssetReference`) so that webpack-bundled files with SWC plugin transforms also receive the correct `NODE_ENV`.
- **`segment_config.rs`**: passes a placeholder but includes a comment explaining it is irrelevant since `EcmascriptInputTransforms::empty()` means no transforms run.

<!-- NEXT_JS_LLM_PR -->
parent 2e916555
......@@ -393,6 +393,9 @@ pub async fn parse_segment_config_from_source(
EcmascriptModuleAssetType::Ecmascript
},
EcmascriptInputTransforms::empty(),
// node_env is not used here: EcmascriptInputTransforms::empty() means no
// transforms are applied, so TransformContext::node_env is never accessed.
rcstr!("development"),
false,
false,
)
......
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
// ENV_CHECK will be replaced by the SWC plugin with "development" or "production"
declare const ENV_CHECK: string
export default function Home() {
return <main>The SWC plugin received env={ENV_CHECK}</main>
}
import { nextTestSetup } from 'e2e-utils'
describe('swc-plugins-env', () => {
const { next, skipped, isNextDev } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
it('should pass correct environment to swc plugins', async () => {
const $ = await next.render$('/')
if (isNextDev) {
expect($('main').text()).toBe('The SWC plugin received env=development')
} else {
expect($('main').text()).toBe('The SWC plugin received env=production')
}
})
})
/** @type {import('next').NextConfig} */
module.exports = {
experimental: {
swcPlugins: [['./swc_plugin_env_check.wasm', {}]],
},
}
This diff is collapsed.
[package]
name = "swc-plugin-env-check"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[profile.release]
strip = "debuginfo"
codegen-units = 1
lto = true
opt-level = "z"
[dependencies]
serde = "1.0.173"
serde_json = "1.0.103"
swc_core = { version = "63.1.1", features = ["ecma_plugin_transform"] }
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use swc_core::{
common::DUMMY_SP,
ecma::{
ast::*,
visit::{VisitMut, VisitMutWith, visit_mut_pass},
},
plugin::{
metadata::TransformPluginMetadataContextKind, plugin_transform,
proxies::TransformPluginProgramMetadata,
},
};
struct EnvCheckVisitor {
env_name: String,
}
impl VisitMut for EnvCheckVisitor {
fn visit_mut_expr(&mut self, expr: &mut Expr) {
expr.visit_mut_children_with(self);
// Replace any identifier `ENV_CHECK` with a string literal of the actual env value
if let Expr::Ident(ident) = expr {
if ident.sym.as_str() == "ENV_CHECK" {
*expr = Expr::Lit(Lit::Str(Str {
span: DUMMY_SP,
value: self.env_name.clone().into(),
raw: None,
}));
}
}
}
}
#[plugin_transform]
pub fn process_transform(program: Program, metadata: TransformPluginProgramMetadata) -> Program {
let env_name = metadata
.get_context(&TransformPluginMetadataContextKind::Env)
.expect("failed to get env");
program.apply(visit_mut_pass(&mut EnvCheckVisitor { env_name }))
}
......@@ -9,7 +9,7 @@ use bincode::{Decode, Encode};
use indexmap::Equivalent;
use num_bigint::BigInt;
use rustc_hash::FxHashSet;
use smallvec::SmallVec;
use smallvec::{SmallVec, smallvec};
use turbo_rcstr::RcStr;
use turbo_tasks::{FxIndexMap, NonLocalValue, ResolvedVc, Vc, trace::TraceRawVcs};
use turbo_tasks_fs::FileSystemPath;
......@@ -340,6 +340,19 @@ impl CompileTimeDefines {
pub fn empty() -> Vc<Self> {
Vc::cell(FxIndexMap::default())
}
#[turbo_tasks::function]
pub async fn read_process_env(&self, key: RcStr) -> Result<Vc<Option<RcStr>>> {
let key = DefinableNameSegmentRefs(smallvec![
DefinableNameSegmentRef::Name("process"),
DefinableNameSegmentRef::Name("env"),
DefinableNameSegmentRef::Name(&key),
]);
Ok(Vc::cell(match self.0.get(&key) {
Some(CompileTimeDefineValue::String(s)) => Some(s.clone()),
_ => None,
}))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, TraceRawVcs, NonLocalValue, Encode, Decode)]
......
......@@ -163,8 +163,7 @@ impl CustomTransformer for SwcEcmaTransformPluginsTransformer {
let transform_metadata_context = Arc::new(TransformPluginMetadataContext::new(
Some(ctx.file_path_str.to_string()),
//[TODO]: Support env-related variable injection, i.e process.env.NODE_ENV
"development".to_string(),
ctx.node_env.to_string(),
None,
));
......
......@@ -701,10 +701,19 @@ impl EcmascriptModuleAsset {
impl EcmascriptModuleAsset {
pub async fn parse(&self) -> Result<Vc<ParseResult>> {
let options = self.options.await?;
let node_env = self
.compile_time_info
.await?
.defines
.read_process_env(rcstr!("NODE_ENV"))
.owned()
.await?
.unwrap_or_else(|| rcstr!("development"));
Ok(parse(
*self.source,
self.ty,
*self.transforms,
node_env,
options.analyze_mode == AnalyzeMode::Tracing,
options.inline_helpers,
))
......
......@@ -268,6 +268,7 @@ pub async fn parse(
source: ResolvedVc<Box<dyn Source>>,
ty: EcmascriptModuleAssetType,
transforms: ResolvedVc<EcmascriptInputTransforms>,
node_env: RcStr,
is_external_tracing: bool,
inline_helpers: bool,
) -> Result<Vc<ParseResult>> {
......@@ -277,9 +278,16 @@ pub async fn parse(
ty = display(&ty)
);
match parse_internal(source, ty, transforms, is_external_tracing, inline_helpers)
.instrument(span)
.await
match parse_internal(
source,
ty,
transforms,
node_env,
is_external_tracing,
inline_helpers,
)
.instrument(span)
.await
{
Ok(result) => Ok(result),
// ast-grep-ignore: no-context-turbofmt
......@@ -291,6 +299,7 @@ async fn parse_internal(
source: ResolvedVc<Box<dyn Source>>,
ty: EcmascriptModuleAssetType,
transforms: ResolvedVc<EcmascriptInputTransforms>,
node_env: RcStr,
loose_errors: bool,
inline_helpers: bool,
) -> Result<Vc<ParseResult>> {
......@@ -336,6 +345,7 @@ async fn parse_internal(
source,
ty,
transforms,
node_env.clone(),
loose_errors,
inline_helpers,
)
......@@ -396,6 +406,7 @@ async fn parse_file_content(
source: ResolvedVc<Box<dyn Source>>,
ty: EcmascriptModuleAssetType,
transforms: &[EcmascriptInputTransform],
node_env: RcStr,
loose_errors: bool,
inline_helpers: bool,
) -> Result<Vc<ParseResult>> {
......@@ -552,6 +563,7 @@ async fn parse_file_content(
query_str: query,
file_path: fs_path.clone(),
source,
node_env,
};
let span = tracing::trace_span!("transforms");
async {
......
......@@ -134,6 +134,9 @@ pub struct TransformContext<'a> {
pub query_str: RcStr,
pub file_path: FileSystemPath,
pub source: ResolvedVc<Box<dyn Source>>,
/// The value of `process.env.NODE_ENV` for this compilation
/// (e.g. `"development"` or `"production"`).
pub node_env: RcStr,
}
impl EcmascriptInputTransform {
......
......@@ -3,6 +3,7 @@ use swc_core::ecma::ast::Lit;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use turbopack_core::{
compile_time_info::CompileTimeInfo,
file_source::FileSource,
ident::AssetIdent,
module::{Module, ModuleSideEffects},
......@@ -27,6 +28,7 @@ pub struct WebpackModuleAsset {
pub source: ResolvedVc<Box<dyn Source>>,
pub runtime: ResolvedVc<WebpackRuntime>,
pub transforms: ResolvedVc<EcmascriptInputTransforms>,
pub compile_time_info: ResolvedVc<CompileTimeInfo>,
}
#[turbo_tasks::value_impl]
......@@ -36,11 +38,13 @@ impl WebpackModuleAsset {
source: ResolvedVc<Box<dyn Source>>,
runtime: ResolvedVc<WebpackRuntime>,
transforms: ResolvedVc<EcmascriptInputTransforms>,
compile_time_info: ResolvedVc<CompileTimeInfo>,
) -> Vc<Self> {
Self::cell(WebpackModuleAsset {
source,
runtime,
transforms,
compile_time_info,
})
}
}
......@@ -59,7 +63,12 @@ impl Module for WebpackModuleAsset {
#[turbo_tasks::function]
fn references(&self) -> Vc<ModuleReferences> {
module_references(*self.source, *self.runtime, *self.transforms)
module_references(
*self.source,
*self.runtime,
*self.transforms,
*self.compile_time_info,
)
}
#[turbo_tasks::function]
......@@ -77,6 +86,7 @@ pub struct WebpackChunkAssetReference {
pub chunk_id: Lit,
pub runtime: ResolvedVc<WebpackRuntime>,
pub transforms: ResolvedVc<EcmascriptInputTransforms>,
pub compile_time_info: ResolvedVc<CompileTimeInfo>,
}
impl WebpackChunkAssetReference {
......@@ -109,9 +119,14 @@ impl ModuleReference for WebpackChunkAssetReference {
let source = Vc::upcast(FileSource::new(context_path.join(&filename)?));
*ModuleResolveResult::module(ResolvedVc::upcast(
WebpackModuleAsset::new(source, *self.runtime, *self.transforms)
.to_resolved()
.await?,
WebpackModuleAsset::new(
source,
*self.runtime,
*self.transforms,
*self.compile_time_info,
)
.to_resolved()
.await?,
))
}
WebpackRuntime::None => *ModuleResolveResult::unresolvable(),
......@@ -126,6 +141,7 @@ pub struct WebpackEntryAssetReference {
pub source: ResolvedVc<Box<dyn Source>>,
pub runtime: ResolvedVc<WebpackRuntime>,
pub transforms: ResolvedVc<EcmascriptInputTransforms>,
pub compile_time_info: ResolvedVc<CompileTimeInfo>,
}
#[turbo_tasks::value_impl]
......@@ -133,9 +149,14 @@ impl ModuleReference for WebpackEntryAssetReference {
#[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
Ok(*ModuleResolveResult::module(ResolvedVc::upcast(
WebpackModuleAsset::new(*self.source, *self.runtime, *self.transforms)
.to_resolved()
.await?,
WebpackModuleAsset::new(
*self.source,
*self.runtime,
*self.transforms,
*self.compile_time_info,
)
.to_resolved()
.await?,
)))
}
}
......@@ -148,6 +169,7 @@ pub struct WebpackRuntimeAssetReference {
pub request: ResolvedVc<Request>,
pub runtime: ResolvedVc<WebpackRuntime>,
pub transforms: ResolvedVc<EcmascriptInputTransforms>,
pub compile_time_info: ResolvedVc<CompileTimeInfo>,
}
#[turbo_tasks::value_impl]
......@@ -169,9 +191,14 @@ impl ModuleReference for WebpackRuntimeAssetReference {
.await?
.map_module(|source| async move {
Ok(ModuleResolveResultItem::Module(ResolvedVc::upcast(
WebpackModuleAsset::new(*source, *self.runtime, *self.transforms)
.to_resolved()
.await?,
WebpackModuleAsset::new(
*source,
*self.runtime,
*self.transforms,
*self.compile_time_info,
)
.to_resolved()
.await?,
)))
})
.await?
......
......@@ -12,9 +12,10 @@ use swc_core::{
visit::{Visit, VisitWith},
},
};
use turbo_rcstr::rcstr;
use turbo_tasks::Vc;
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::source::Source;
use turbopack_core::{compile_time_info::CompileTimeInfo, source::Source};
use crate::{
EcmascriptInputTransforms, EcmascriptModuleAssetType,
......@@ -189,11 +190,20 @@ fn get_require_prefix(stmts: &Vec<Stmt>) -> Option<Lit> {
pub async fn webpack_runtime(
source: Vc<Box<dyn Source>>,
transforms: Vc<EcmascriptInputTransforms>,
compile_time_info: Vc<CompileTimeInfo>,
) -> Result<Vc<WebpackRuntime>> {
let node_env = compile_time_info
.await?
.defines
.read_process_env(rcstr!("NODE_ENV"))
.owned()
.await?
.unwrap_or_else(|| rcstr!("development"));
let parsed = parse(
source,
EcmascriptModuleAssetType::Ecmascript,
transforms,
node_env,
false,
false,
)
......
......@@ -9,6 +9,7 @@ use swc_core::{
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc};
use turbopack_core::{
compile_time_info::CompileTimeInfo,
reference::{ModuleReference, ModuleReferences},
source::Source,
};
......@@ -25,11 +26,20 @@ pub async fn module_references(
source: ResolvedVc<Box<dyn Source>>,
runtime: ResolvedVc<WebpackRuntime>,
transforms: ResolvedVc<EcmascriptInputTransforms>,
compile_time_info: ResolvedVc<CompileTimeInfo>,
) -> Result<Vc<ModuleReferences>> {
let node_env = compile_time_info
.await?
.defines
.read_process_env(rcstr!("NODE_ENV"))
.owned()
.await?
.unwrap_or_else(|| rcstr!("development"));
let parsed = parse(
*source,
EcmascriptModuleAssetType::Ecmascript,
*transforms,
node_env,
false,
false,
)
......@@ -45,6 +55,7 @@ pub async fn module_references(
references: &mut references,
runtime,
transforms,
compile_time_info,
};
let (emitter, collector) = IssueEmitter::new(
source,
......@@ -66,6 +77,7 @@ struct ModuleReferencesVisitor<'a> {
runtime: ResolvedVc<WebpackRuntime>,
references: &'a mut Vec<ResolvedVc<Box<dyn ModuleReference>>>,
transforms: ResolvedVc<EcmascriptInputTransforms>,
compile_time_info: ResolvedVc<CompileTimeInfo>,
}
impl Visit for ModuleReferencesVisitor<'_> {
......@@ -82,6 +94,7 @@ impl Visit for ModuleReferencesVisitor<'_> {
chunk_id: lit.clone(),
runtime: self.runtime,
transforms: self.transforms,
compile_time_info: self.compile_time_info,
}
.resolved_cell(),
));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment