Skip to content

Commit 0320211

Browse files
committed
Turbopack: set env in tracing context
1 parent 0985b23 commit 0320211

File tree

3 files changed

+79
-25
lines changed

3 files changed

+79
-25
lines changed

crates/next-core/src/next_server/context.rs

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ use turbo_tasks_fs::FileSystemPath;
88
use turbopack::{
99
css::chunk::CssChunkType,
1010
module_options::{
11-
CssOptionsContext, EcmascriptOptionsContext, JsxTransformOptions, ModuleOptionsContext,
12-
ModuleRule, TypeofWindow, TypescriptTransformOptions,
11+
CssOptionsContext, EcmascriptOptionsContext, ExternalsTracingOptions, JsxTransformOptions,
12+
ModuleOptionsContext, ModuleRule, TypeofWindow, TypescriptTransformOptions,
1313
},
1414
resolve_options_context::ResolveOptionsContext,
1515
transition::Transition,
@@ -19,6 +19,7 @@ use turbopack_core::{
1919
ChunkingConfig, MangleType, MinifyType, SourceMapsType,
2020
module_id_strategies::ModuleIdStrategy,
2121
},
22+
compile_time_defines,
2223
compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReferences},
2324
environment::{
2425
Environment, ExecutionEnvironment, NodeJsEnvironment, NodeJsVersion, RuntimeVersions,
@@ -387,6 +388,49 @@ pub async fn get_server_compile_time_info(
387388
.await
388389
}
389390

391+
#[turbo_tasks::function]
392+
pub async fn get_tracing_compile_time_info() -> Result<Vc<CompileTimeInfo>> {
393+
CompileTimeInfo::builder(
394+
Environment::new(ExecutionEnvironment::NodeJsLambda(
395+
NodeJsEnvironment::default().resolved_cell(),
396+
))
397+
.to_resolved()
398+
.await?,
399+
)
400+
/*
401+
We'd really like to set `process.env.NODE_ENV = "production"` here, but with that,
402+
`react/cjs/react.development.js` won't be copied anymore (as expected).
403+
However if you `import` react from native ESM: `import {createContext} from 'react';`, it fails with
404+
```
405+
import {createContext} from 'react';
406+
^^^^^^^^^^^^^
407+
SyntaxError: Named export 'createContext' not found. The requested module 'react' is a CommonJS module, which may not support all module.exports as named exports.
408+
CommonJS modules can always be imported via the default export, for example using:
409+
```
410+
This is because Node's import-cjs-from-esm feature can correctly find all named exports in
411+
```
412+
// `react/index.js`
413+
if (process.env.NODE_ENV === 'production') {
414+
module.exports = require('./cjs/react.production.js');
415+
} else {
416+
module.exports = require('./cjs/react.development.js');
417+
}
418+
```
419+
if both files exist (which is what's happening so far).
420+
If `react.development.js` doesn't exist, then it bails with that error message.
421+
Also just removing that second branch works fine, but a `require` to a non-existent file fails.
422+
*/
423+
.defines(
424+
compile_time_defines!(
425+
process.env.TURBOPACK = true,
426+
// process.env.NODE_ENV = "production",
427+
)
428+
.resolved_cell(),
429+
)
430+
.cell()
431+
.await
432+
}
433+
390434
#[turbo_tasks::function]
391435
pub async fn get_server_module_options_context(
392436
project_path: FileSystemPath,
@@ -544,7 +588,13 @@ pub async fn get_server_module_options_context(
544588
tree_shaking_mode: tree_shaking_mode_for_user_code,
545589
side_effect_free_packages: next_config.optimize_package_imports().owned().await?,
546590
enable_externals_tracing: if next_mode.is_production() {
547-
Some(project_path)
591+
Some(
592+
ExternalsTracingOptions {
593+
tracing_root: project_path,
594+
compile_time_info: get_tracing_compile_time_info().to_resolved().await?,
595+
}
596+
.resolved_cell(),
597+
)
548598
} else {
549599
None
550600
},

turbopack/crates/turbopack/src/lib.rs

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ use turbopack_core::{
3434
chunk::SourceMapsType,
3535
compile_time_info::CompileTimeInfo,
3636
context::{AssetContext, ProcessResult},
37-
environment::{Environment, ExecutionEnvironment, NodeJsEnvironment},
3837
ident::Layer,
3938
issue::{IssueExt, IssueSource, StyledString, module::ModuleIssue},
4039
module::Module,
@@ -643,15 +642,12 @@ async fn process_default_internal(
643642
}
644643

645644
#[turbo_tasks::function]
646-
async fn externals_tracing_module_context(ty: ExternalType) -> Result<Vc<ModuleAssetContext>> {
647-
let env = Environment::new(ExecutionEnvironment::NodeJsLambda(
648-
NodeJsEnvironment::default().resolved_cell(),
649-
))
650-
.to_resolved()
651-
.await?;
652-
645+
async fn externals_tracing_module_context(
646+
ty: ExternalType,
647+
compile_time_info: Vc<CompileTimeInfo>,
648+
) -> Result<Vc<ModuleAssetContext>> {
653649
let resolve_options = ResolveOptionsContext {
654-
emulate_environment: Some(env),
650+
emulate_environment: Some(compile_time_info.await?.environment),
655651
loose_errors: true,
656652
custom_conditions: match ty {
657653
ExternalType::CommonJs => vec![rcstr!("require")],
@@ -663,7 +659,7 @@ async fn externals_tracing_module_context(ty: ExternalType) -> Result<Vc<ModuleA
663659

664660
Ok(ModuleAssetContext::new_without_replace_externals(
665661
Default::default(),
666-
CompileTimeInfo::builder(env).cell().await?,
662+
compile_time_info,
667663
// Keep these options more or less in sync with
668664
// turbopack/crates/turbopack/tests/node-file-trace.rs to ensure that the NFT unit tests
669665
// are actually representative of what Turbopack does.
@@ -784,7 +780,7 @@ impl AssetContext for ModuleAssetContext {
784780
ResolveResultItem::External { name, ty, traced } => {
785781
let replacement = if replace_externals {
786782
let tracing_mode = if traced == ExternalTraced::Traced
787-
&& let Some(tracing_root) = &self
783+
&& let Some(options) = &self
788784
.module_options_context()
789785
.await?
790786
.enable_externals_tracing
@@ -793,13 +789,17 @@ impl AssetContext for ModuleAssetContext {
793789
// request will later be resolved relative to tracing_root
794790
// anyway.
795791

792+
let options = options.await?;
796793
CachedExternalTracingMode::Traced {
797794
externals_context: ResolvedVc::upcast(
798-
externals_tracing_module_context(ty)
799-
.to_resolved()
800-
.await?,
795+
externals_tracing_module_context(
796+
ty,
797+
*options.compile_time_info,
798+
)
799+
.to_resolved()
800+
.await?,
801801
),
802-
root_origin: tracing_root.join("_")?,
802+
root_origin: options.tracing_root.join("_")?,
803803
}
804804
} else {
805805
CachedExternalTracingMode::Untraced

turbopack/crates/turbopack/src/module_options/module_options_context.rs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ use turbo_rcstr::RcStr;
66
use turbo_tasks::{FxIndexMap, NonLocalValue, ResolvedVc, ValueDefault, Vc, trace::TraceRawVcs};
77
use turbo_tasks_fs::FileSystemPath;
88
use turbopack_core::{
9-
chunk::SourceMapsType, condition::ContextCondition, environment::Environment,
10-
resolve::options::ImportMapping,
9+
chunk::SourceMapsType, compile_time_info::CompileTimeInfo, condition::ContextCondition,
10+
environment::Environment, resolve::options::ImportMapping,
1111
};
1212
use turbopack_ecmascript::{TreeShakingMode, references::esm::UrlRewriteBehavior};
1313
pub use turbopack_mdx::MdxTransformOptions;
@@ -121,7 +121,6 @@ impl ValueDefault for TypescriptTransformOptions {
121121
}
122122
}
123123

124-
// [TODO]: should enabled_react_refresh belong to this options?
125124
#[turbo_tasks::value(shared)]
126125
#[derive(Default, Clone, Debug)]
127126
pub struct JsxTransformOptions {
@@ -131,6 +130,14 @@ pub struct JsxTransformOptions {
131130
pub runtime: Option<RcStr>,
132131
}
133132

133+
#[turbo_tasks::value(shared)]
134+
#[derive(Clone, Debug)]
135+
pub struct ExternalsTracingOptions {
136+
/// The directory from which the bundled files will require the externals at runtime.
137+
pub tracing_root: FileSystemPath,
138+
pub compile_time_info: ResolvedVc<CompileTimeInfo>,
139+
}
140+
134141
#[turbo_tasks::value(shared)]
135142
#[derive(Clone, Default)]
136143
#[serde(default)]
@@ -152,10 +159,7 @@ pub struct ModuleOptionsContext {
152159

153160
/// Generate (non-emitted) output assets for static assets and externals, to facilitate
154161
/// generating a list of all non-bundled files that will be required at runtime.
155-
///
156-
/// The filepath is the directory from which the bundled files will require the externals at
157-
/// runtime.
158-
pub enable_externals_tracing: Option<FileSystemPath>,
162+
pub enable_externals_tracing: Option<ResolvedVc<ExternalsTracingOptions>>,
159163

160164
/// If true, it stores the last successful parse result in state and keeps using it when
161165
/// parsing fails. This is useful to keep the module graph structure intact when syntax errors

0 commit comments

Comments
 (0)