Unverified Commit bb1a5728 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: inner graph tree shaking (#85973)

Alias "unused import removal"

Closes PACK-5782

Performance:

```
* 58fe2e2e377d877f51f91f50770310d2bbf20987 - WIP: enable by default

pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  380.01s user 53.74s system 691% cpu 1:02.76 total
pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  384.99s user 51.00s system 708% cpu 1:01.57 total
pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  381.52s user 46.86s system 711% cpu 1:00.21 total

vs canary:
* f6c2d491 - Turbopack: add task_id_details feature (#84970)

pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  374.87s user 48.47s system 760% cpu 55.662 total
pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  379.18s user 50.27s system 700% cpu 1:01.28 total
pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  370.39s user 45.93s system 726% cpu 57.305 total
pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  372.70s user 46.24s system 717% cpu 58.364 total
```
parent 4deba0f6
...@@ -430,15 +430,17 @@ pub async fn analyze_module_graphs(module_graphs: Vc<ModuleGraphs>) -> Result<Vc ...@@ -430,15 +430,17 @@ pub async fn analyze_module_graphs(module_graphs: Vc<ModuleGraphs>) -> Result<Vc
let mut all_async_edges = FxIndexSet::default(); let mut all_async_edges = FxIndexSet::default();
for &module_graph in module_graphs.await? { for &module_graph in module_graphs.await? {
let module_graph = module_graph.read_graphs().await?; let module_graph = module_graph.read_graphs().await?;
module_graph.traverse_all_edges_unordered(|(parent_node, reference), node| { module_graph.traverse_all_edges_unordered(|parent, node| {
all_modules.insert(parent_node); if let Some((parent_node, reference)) = parent {
all_modules.insert(node); all_modules.insert(parent_node);
match reference.chunking_type { all_modules.insert(node);
ChunkingType::Async => { match reference.chunking_type {
all_async_edges.insert((parent_node, node)); ChunkingType::Async => {
} all_async_edges.insert((parent_node, node));
_ => { }
all_edges.insert((parent_node, node)); _ => {
all_edges.insert((parent_node, node));
}
} }
} }
Ok(()) Ok(())
......
...@@ -59,6 +59,7 @@ use turbopack_core::{ ...@@ -59,6 +59,7 @@ use turbopack_core::{
module::Module, module::Module,
module_graph::{ module_graph::{
GraphEntries, ModuleGraph, SingleModuleGraph, VisitedModules, GraphEntries, ModuleGraph, SingleModuleGraph, VisitedModules,
binding_usage_info::compute_binding_usage_info,
chunk_group_info::{ChunkGroup, ChunkGroupEntry}, chunk_group_info::{ChunkGroup, ChunkGroupEntry},
}, },
output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced}, output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced},
...@@ -856,7 +857,8 @@ impl AppProject { ...@@ -856,7 +857,8 @@ impl AppProject {
has_layout_segments: bool, has_layout_segments: bool,
) -> Result<Vc<BaseAndFullModuleGraph>> { ) -> Result<Vc<BaseAndFullModuleGraph>> {
if *self.project.per_page_module_graph().await? { if *self.project.per_page_module_graph().await? {
let should_trace = self.project.next_mode().await?.is_production(); let next_mode = self.project.next_mode();
let should_trace = next_mode.await?.is_production();
let client_shared_entries = client_shared_entries let client_shared_entries = client_shared_entries
.await? .await?
.into_iter() .into_iter()
...@@ -949,10 +951,31 @@ impl AppProject { ...@@ -949,10 +951,31 @@ impl AppProject {
); );
graphs.push(additional_module_graph); graphs.push(additional_module_graph);
let full = ModuleGraph::from_graphs(graphs); let full_with_unused_references =
ModuleGraph::from_graphs(graphs).to_resolved().await?;
let full = if *self
.project
.next_config()
.turbopack_remove_unused_imports(next_mode)
.await?
{
full_with_unused_references
.without_unused_references(
*compute_binding_usage_info(full_with_unused_references, true)
.resolve_strongly_consistent()
.await?,
)
.to_resolved()
.await?
} else {
full_with_unused_references
};
Ok(BaseAndFullModuleGraph { Ok(BaseAndFullModuleGraph {
base: base.to_resolved().await?, base: base.to_resolved().await?,
full: full.to_resolved().await?, full_with_unused_references,
full,
} }
.cell()) .cell())
} }
......
This diff is collapsed.
...@@ -54,6 +54,7 @@ use turbopack_core::{ ...@@ -54,6 +54,7 @@ use turbopack_core::{
module::Module, module::Module,
module_graph::{ module_graph::{
GraphEntries, ModuleGraph, SingleModuleGraph, VisitedModules, GraphEntries, ModuleGraph, SingleModuleGraph, VisitedModules,
binding_usage_info::compute_binding_usage_info,
chunk_group_info::{ChunkGroup, ChunkGroupEntry}, chunk_group_info::{ChunkGroup, ChunkGroupEntry},
}, },
output::{OptionOutputAsset, OutputAsset, OutputAssets}, output::{OptionOutputAsset, OutputAsset, OutputAssets},
...@@ -726,7 +727,8 @@ impl PageEndpoint { ...@@ -726,7 +727,8 @@ impl PageEndpoint {
let project = this.pages_project.project(); let project = this.pages_project.project();
if *project.per_page_module_graph().await? { if *project.per_page_module_graph().await? {
let should_trace = project.next_mode().await?.is_production(); let next_mode = project.next_mode();
let should_trace = next_mode.await?.is_production();
let ssr_chunk_module = self.internal_ssr_chunk_module().await?; let ssr_chunk_module = self.internal_ssr_chunk_module().await?;
// Implements layout segment optimization to compute a graph "chain" for document, app, // Implements layout segment optimization to compute a graph "chain" for document, app,
// page // page
...@@ -755,7 +757,21 @@ impl PageEndpoint { ...@@ -755,7 +757,21 @@ impl PageEndpoint {
); );
graphs.push(graph); graphs.push(graph);
Ok(ModuleGraph::from_graphs(graphs)) let mut graph = ModuleGraph::from_graphs(graphs);
if *project
.next_config()
.turbopack_remove_unused_imports(next_mode)
.await?
{
graph = graph.without_unused_references(
*compute_binding_usage_info(graph.to_resolved().await?, true)
.resolve_strongly_consistent()
.await?,
);
}
Ok(graph)
} else { } else {
Ok(*project.whole_app_module_graphs().await?.full) Ok(*project.whole_app_module_graphs().await?.full)
} }
......
...@@ -59,8 +59,10 @@ use turbopack_core::{ ...@@ -59,8 +59,10 @@ use turbopack_core::{
module::Module, module::Module,
module_graph::{ module_graph::{
GraphEntries, ModuleGraph, SingleModuleGraph, VisitedModules, GraphEntries, ModuleGraph, SingleModuleGraph, VisitedModules,
binding_usage_info::{
BindingUsageInfo, OptionBindingUsageInfo, compute_binding_usage_info,
},
chunk_group_info::ChunkGroupEntry, chunk_group_info::ChunkGroupEntry,
export_usage::{OptionExportUsageInfo, compute_export_usage_info},
}, },
output::{ output::{
ExpandOutputAssetsInput, ExpandedOutputAssets, OutputAsset, OutputAssets, ExpandOutputAssetsInput, ExpandedOutputAssets, OutputAsset, OutputAssets,
...@@ -1165,6 +1167,7 @@ impl Project { ...@@ -1165,6 +1167,7 @@ impl Project {
environment: self.client_compile_time_info().environment(), environment: self.client_compile_time_info().environment(),
module_id_strategy: self.module_ids(), module_id_strategy: self.module_ids(),
export_usage: self.export_usage(), export_usage: self.export_usage(),
unused_references: self.unused_references(),
minify: self.next_config().turbo_minify(self.next_mode()), minify: self.next_config().turbo_minify(self.next_mode()),
source_maps: self.next_config().client_source_maps(self.next_mode()), source_maps: self.next_config().client_source_maps(self.next_mode()),
no_mangling: self.no_mangling(), no_mangling: self.no_mangling(),
...@@ -1190,6 +1193,7 @@ impl Project { ...@@ -1190,6 +1193,7 @@ impl Project {
environment: self.server_compile_time_info().environment(), environment: self.server_compile_time_info().environment(),
module_id_strategy: self.module_ids(), module_id_strategy: self.module_ids(),
export_usage: self.export_usage(), export_usage: self.export_usage(),
unused_references: self.unused_references(),
minify: self.next_config().turbo_minify(self.next_mode()), minify: self.next_config().turbo_minify(self.next_mode()),
source_maps: self.next_config().server_source_maps(), source_maps: self.next_config().server_source_maps(),
no_mangling: self.no_mangling(), no_mangling: self.no_mangling(),
...@@ -1221,6 +1225,7 @@ impl Project { ...@@ -1221,6 +1225,7 @@ impl Project {
environment: self.edge_compile_time_info().environment(), environment: self.edge_compile_time_info().environment(),
module_id_strategy: self.module_ids(), module_id_strategy: self.module_ids(),
export_usage: self.export_usage(), export_usage: self.export_usage(),
unused_references: self.unused_references(),
turbo_minify: self.next_config().turbo_minify(self.next_mode()), turbo_minify: self.next_config().turbo_minify(self.next_mode()),
turbo_source_maps: self.next_config().server_source_maps(), turbo_source_maps: self.next_config().server_source_maps(),
no_mangling: self.no_mangling(), no_mangling: self.no_mangling(),
...@@ -1925,20 +1930,50 @@ impl Project { ...@@ -1925,20 +1930,50 @@ impl Project {
} }
} }
/// Compute the used exports and unused imports for each module.
#[turbo_tasks::function]
async fn binding_usage_info(self: Vc<Self>) -> Result<Vc<BindingUsageInfo>> {
let remove_unused_imports = *self
.next_config()
.turbopack_remove_unused_imports(self.next_mode())
.await?;
let module_graphs = self.whole_app_module_graphs().await?;
Ok(*compute_binding_usage_info(
module_graphs.full_with_unused_references,
remove_unused_imports,
)
// As a performance optimization, we resolve strongly consistently
.resolve_strongly_consistent()
.await?)
}
/// Compute the used exports for each module. /// Compute the used exports for each module.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn export_usage(self: Vc<Self>) -> Result<Vc<OptionExportUsageInfo>> { pub async fn export_usage(self: Vc<Self>) -> Result<Vc<OptionBindingUsageInfo>> {
if *self if *self
.next_config() .next_config()
.turbopack_remove_unused_exports(self.next_mode()) .turbopack_remove_unused_exports(self.next_mode())
.await? .await?
{ {
let module_graphs = self.whole_app_module_graphs().await?;
Ok(Vc::cell(Some( Ok(Vc::cell(Some(
compute_export_usage_info(module_graphs.full) self.binding_usage_info().to_resolved().await?,
// As a performance optimization, we resolve strongly consistently )))
.resolve_strongly_consistent() } else {
.await?, Ok(Vc::cell(None))
}
}
/// Compute the unused references that were removed (inner graph tree shaking).
#[turbo_tasks::function]
pub async fn unused_references(self: Vc<Self>) -> Result<Vc<OptionBindingUsageInfo>> {
if *self
.next_config()
.turbopack_remove_unused_imports(self.next_mode())
.await?
{
Ok(Vc::cell(Some(
self.binding_usage_info().to_resolved().await?,
))) )))
} else { } else {
Ok(Vc::cell(None)) Ok(Vc::cell(None))
...@@ -1963,12 +1998,31 @@ async fn whole_app_module_graph_operation( ...@@ -1963,12 +1998,31 @@ async fn whole_app_module_graph_operation(
) -> Result<Vc<BaseAndFullModuleGraph>> { ) -> Result<Vc<BaseAndFullModuleGraph>> {
mark_root(); mark_root();
let should_trace = project.next_mode().await?.is_production(); let next_mode = project.next_mode();
let should_trace = next_mode.await?.is_production();
let base_single_module_graph = let base_single_module_graph =
SingleModuleGraph::new_with_entries(project.get_all_entries(), should_trace); SingleModuleGraph::new_with_entries(project.get_all_entries(), should_trace);
let base_visited_modules = VisitedModules::from_graph(base_single_module_graph); let base_visited_modules = VisitedModules::from_graph(base_single_module_graph);
let base = ModuleGraph::from_single_graph(base_single_module_graph); let base = ModuleGraph::from_single_graph(base_single_module_graph);
let turbopack_remove_unused_imports = *project
.next_config()
.turbopack_remove_unused_imports(next_mode)
.await?;
let base = if turbopack_remove_unused_imports {
// TODO suboptimal that we do compute_binding_usage_info twice (once for the base graph
// and later for the full graph)
base.without_unused_references(
*compute_binding_usage_info(base.to_resolved().await?, true)
.resolve_strongly_consistent()
.await?,
)
} else {
base
};
let additional_entries = project.get_all_additional_entries(base); let additional_entries = project.get_all_additional_entries(base);
let additional_module_graph = SingleModuleGraph::new_with_entries_visited( let additional_module_graph = SingleModuleGraph::new_with_entries_visited(
...@@ -1977,17 +2031,40 @@ async fn whole_app_module_graph_operation( ...@@ -1977,17 +2031,40 @@ async fn whole_app_module_graph_operation(
should_trace, should_trace,
); );
let full = ModuleGraph::from_graphs(vec![base_single_module_graph, additional_module_graph]); let full_with_unused_references =
ModuleGraph::from_graphs(vec![base_single_module_graph, additional_module_graph])
.to_resolved()
.await?;
let full = if turbopack_remove_unused_imports {
full_with_unused_references
.without_unused_references(
*compute_binding_usage_info(full_with_unused_references, true)
.resolve_strongly_consistent()
.await?,
)
.to_resolved()
.await?
} else {
full_with_unused_references
};
Ok(BaseAndFullModuleGraph { Ok(BaseAndFullModuleGraph {
base: base.to_resolved().await?, base: base.to_resolved().await?,
full: full.to_resolved().await?, full_with_unused_references,
full,
} }
.cell()) .cell())
} }
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct BaseAndFullModuleGraph { pub struct BaseAndFullModuleGraph {
/// The base module graph generated from the entry points.
pub base: ResolvedVc<ModuleGraph>, pub base: ResolvedVc<ModuleGraph>,
/// The base graph plus any modules that were generated from additional entries (for which the
/// base graph is needed).
pub full_with_unused_references: ResolvedVc<ModuleGraph>,
/// `full_with_unused_references` but with unused references removed.
pub full: ResolvedVc<ModuleGraph>, pub full: ResolvedVc<ModuleGraph>,
} }
......
...@@ -58,12 +58,14 @@ where ...@@ -58,12 +58,14 @@ where
let asset_reasons = { let asset_reasons = {
let module_graph = module_graph.read_graphs().await?; let module_graph = module_graph.read_graphs().await?;
let mut edges = vec![]; let mut edges = vec![];
module_graph.traverse_all_edges_unordered(|(parent_node, r), current| { module_graph.traverse_all_edges_unordered(|parent, current| {
edges.push(( if let Some((parent_node, r)) = parent {
parent_node, edges.push((
RcStr::from(format!("{}: {}", r.chunking_type, r.export)), parent_node,
current, RcStr::from(format!("{}: {}", r.chunking_type, r.binding_usage.export)),
)); current,
));
}
Ok(()) Ok(())
})?; })?;
......
...@@ -25,7 +25,7 @@ use turbopack_core::{ ...@@ -25,7 +25,7 @@ use turbopack_core::{
compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReference, FreeVarReferences}, compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReference, FreeVarReferences},
environment::{BrowserEnvironment, Environment, ExecutionEnvironment}, environment::{BrowserEnvironment, Environment, ExecutionEnvironment},
free_var_references, free_var_references,
module_graph::export_usage::OptionExportUsageInfo, module_graph::binding_usage_info::OptionBindingUsageInfo,
resolve::{parse::Request, pattern::Pattern}, resolve::{parse::Request, pattern::Pattern},
}; };
use turbopack_ecmascript::{AnalyzeMode, TypeofWindow, chunk::EcmascriptChunkType}; use turbopack_ecmascript::{AnalyzeMode, TypeofWindow, chunk::EcmascriptChunkType};
...@@ -416,7 +416,8 @@ pub struct ClientChunkingContextOptions { ...@@ -416,7 +416,8 @@ pub struct ClientChunkingContextOptions {
pub asset_prefix: Vc<RcStr>, pub asset_prefix: Vc<RcStr>,
pub environment: Vc<Environment>, pub environment: Vc<Environment>,
pub module_id_strategy: Vc<Box<dyn ModuleIdStrategy>>, pub module_id_strategy: Vc<Box<dyn ModuleIdStrategy>>,
pub export_usage: Vc<OptionExportUsageInfo>, pub export_usage: Vc<OptionBindingUsageInfo>,
pub unused_references: Vc<OptionBindingUsageInfo>,
pub minify: Vc<bool>, pub minify: Vc<bool>,
pub source_maps: Vc<SourceMapsType>, pub source_maps: Vc<SourceMapsType>,
pub no_mangling: Vc<bool>, pub no_mangling: Vc<bool>,
...@@ -439,6 +440,7 @@ pub async fn get_client_chunking_context( ...@@ -439,6 +440,7 @@ pub async fn get_client_chunking_context(
environment, environment,
module_id_strategy, module_id_strategy,
export_usage, export_usage,
unused_references,
minify, minify,
source_maps, source_maps,
no_mangling, no_mangling,
...@@ -473,6 +475,7 @@ pub async fn get_client_chunking_context( ...@@ -473,6 +475,7 @@ pub async fn get_client_chunking_context(
.asset_base_path(Some(asset_prefix)) .asset_base_path(Some(asset_prefix))
.current_chunk_method(CurrentChunkMethod::DocumentCurrentScript) .current_chunk_method(CurrentChunkMethod::DocumentCurrentScript)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(*unused_references.await?)
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.debug_ids(*debug_ids.await?) .debug_ids(*debug_ids.await?)
.should_use_absolute_url_references(*should_use_absolute_url_references.await?) .should_use_absolute_url_references(*should_use_absolute_url_references.await?)
......
...@@ -15,7 +15,7 @@ use turbopack_core::{ ...@@ -15,7 +15,7 @@ use turbopack_core::{
context::AssetContext, context::AssetContext,
ident::AssetIdent, ident::AssetIdent,
module::Module, module::Module,
module_graph::{ModuleGraph, export_usage::ModuleExportUsageInfo}, module_graph::{ModuleGraph, binding_usage_info::ModuleExportUsageInfo},
output::OutputAssetsReference, output::OutputAssetsReference,
reference::{ModuleReference, ModuleReferences}, reference::{ModuleReference, ModuleReferences},
reference_type::ReferenceType, reference_type::ReferenceType,
......
...@@ -192,9 +192,9 @@ impl Visit<FindServerEntriesNode> for FindServerEntries { ...@@ -192,9 +192,9 @@ impl Visit<FindServerEntriesNode> for FindServerEntries {
let referenced_modules = referenced_modules let referenced_modules = referenced_modules
.iter() .iter()
.flat_map(|(chunking_type, _, modules)| match chunking_type { .flat_map(|(_, resolved)| match resolved.chunking_type {
ChunkingType::Traced => None, ChunkingType::Traced => None,
_ => Some(modules.iter()), _ => Some(resolved.modules.iter()),
}) })
.flatten() .flatten()
.map(async |module| { .map(async |module| {
......
...@@ -901,6 +901,8 @@ pub struct ExperimentalConfig { ...@@ -901,6 +901,8 @@ pub struct ExperimentalConfig {
// Whether to enable the global-not-found convention // Whether to enable the global-not-found convention
global_not_found: Option<bool>, global_not_found: Option<bool>,
/// Defaults to false in development mode, true in production mode. /// Defaults to false in development mode, true in production mode.
turbopack_remove_unused_imports: Option<bool>,
/// Defaults to false in development mode, true in production mode.
turbopack_remove_unused_exports: Option<bool>, turbopack_remove_unused_exports: Option<bool>,
/// Devtool option for the segment explorer. /// Devtool option for the segment explorer.
devtool_segment_explorer: Option<bool>, devtool_segment_explorer: Option<bool>,
...@@ -1754,6 +1756,27 @@ impl NextConfig { ...@@ -1754,6 +1756,27 @@ impl NextConfig {
.cell() .cell()
} }
#[turbo_tasks::function]
pub async fn turbopack_remove_unused_imports(
self: Vc<Self>,
mode: Vc<NextMode>,
) -> Result<Vc<bool>> {
let remove_unused_imports = self
.await?
.experimental
.turbopack_remove_unused_imports
.unwrap_or(matches!(*mode.await?, NextMode::Build));
if remove_unused_imports && !*self.turbopack_remove_unused_exports(mode).await? {
bail!(
"`experimental.turbopackRemoveUnusedImports` cannot be enabled without also \
enabling `experimental.turbopackRemoveUnusedExports`"
);
}
Ok(Vc::cell(remove_unused_imports))
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn turbopack_remove_unused_exports(&self, mode: Vc<NextMode>) -> Result<Vc<bool>> { pub async fn turbopack_remove_unused_exports(&self, mode: Vc<NextMode>) -> Result<Vc<bool>> {
Ok(Vc::cell( Ok(Vc::cell(
......
...@@ -13,7 +13,7 @@ use turbopack_core::{ ...@@ -13,7 +13,7 @@ use turbopack_core::{
compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReference, FreeVarReferences}, compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReference, FreeVarReferences},
environment::{EdgeWorkerEnvironment, Environment, ExecutionEnvironment, NodeJsVersion}, environment::{EdgeWorkerEnvironment, Environment, ExecutionEnvironment, NodeJsVersion},
free_var_references, free_var_references,
module_graph::export_usage::OptionExportUsageInfo, module_graph::binding_usage_info::OptionBindingUsageInfo,
}; };
use turbopack_ecmascript::chunk::EcmascriptChunkType; use turbopack_ecmascript::chunk::EcmascriptChunkType;
use turbopack_node::execution_context::ExecutionContext; use turbopack_node::execution_context::ExecutionContext;
...@@ -203,7 +203,8 @@ pub struct EdgeChunkingContextOptions { ...@@ -203,7 +203,8 @@ pub struct EdgeChunkingContextOptions {
pub output_root_to_root_path: Vc<RcStr>, pub output_root_to_root_path: Vc<RcStr>,
pub environment: Vc<Environment>, pub environment: Vc<Environment>,
pub module_id_strategy: Vc<Box<dyn ModuleIdStrategy>>, pub module_id_strategy: Vc<Box<dyn ModuleIdStrategy>>,
pub export_usage: Vc<OptionExportUsageInfo>, pub export_usage: Vc<OptionBindingUsageInfo>,
pub unused_references: Vc<OptionBindingUsageInfo>,
pub turbo_minify: Vc<bool>, pub turbo_minify: Vc<bool>,
pub turbo_source_maps: Vc<SourceMapsType>, pub turbo_source_maps: Vc<SourceMapsType>,
pub no_mangling: Vc<bool>, pub no_mangling: Vc<bool>,
...@@ -226,6 +227,7 @@ pub async fn get_edge_chunking_context_with_client_assets( ...@@ -226,6 +227,7 @@ pub async fn get_edge_chunking_context_with_client_assets(
environment, environment,
module_id_strategy, module_id_strategy,
export_usage, export_usage,
unused_references,
turbo_minify, turbo_minify,
turbo_source_maps, turbo_source_maps,
no_mangling, no_mangling,
...@@ -258,6 +260,7 @@ pub async fn get_edge_chunking_context_with_client_assets( ...@@ -258,6 +260,7 @@ pub async fn get_edge_chunking_context_with_client_assets(
.source_maps(*turbo_source_maps.await?) .source_maps(*turbo_source_maps.await?)
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(*unused_references.await?)
.nested_async_availability(*nested_async_chunking.await?); .nested_async_availability(*nested_async_chunking.await?);
if !next_mode.is_development() { if !next_mode.is_development() {
...@@ -295,6 +298,7 @@ pub async fn get_edge_chunking_context( ...@@ -295,6 +298,7 @@ pub async fn get_edge_chunking_context(
environment, environment,
module_id_strategy, module_id_strategy,
export_usage, export_usage,
unused_references,
turbo_minify, turbo_minify,
turbo_source_maps, turbo_source_maps,
no_mangling, no_mangling,
...@@ -333,6 +337,7 @@ pub async fn get_edge_chunking_context( ...@@ -333,6 +337,7 @@ pub async fn get_edge_chunking_context(
.source_maps(*turbo_source_maps.await?) .source_maps(*turbo_source_maps.await?)
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(*unused_references.await?)
.nested_async_availability(*nested_async_chunking.await?); .nested_async_availability(*nested_async_chunking.await?);
if !next_mode.is_development() { if !next_mode.is_development() {
......
...@@ -23,7 +23,7 @@ use turbopack_core::{ ...@@ -23,7 +23,7 @@ use turbopack_core::{
compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReferences}, compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReferences},
environment::{Environment, ExecutionEnvironment, NodeJsEnvironment, NodeJsVersion}, environment::{Environment, ExecutionEnvironment, NodeJsEnvironment, NodeJsVersion},
free_var_references, free_var_references,
module_graph::export_usage::OptionExportUsageInfo, module_graph::binding_usage_info::OptionBindingUsageInfo,
target::CompileTarget, target::CompileTarget,
}; };
use turbopack_ecmascript::{ use turbopack_ecmascript::{
...@@ -991,7 +991,8 @@ pub struct ServerChunkingContextOptions { ...@@ -991,7 +991,8 @@ pub struct ServerChunkingContextOptions {
pub node_root_to_root_path: RcStr, pub node_root_to_root_path: RcStr,
pub environment: Vc<Environment>, pub environment: Vc<Environment>,
pub module_id_strategy: Vc<Box<dyn ModuleIdStrategy>>, pub module_id_strategy: Vc<Box<dyn ModuleIdStrategy>>,
pub export_usage: Vc<OptionExportUsageInfo>, pub export_usage: Vc<OptionBindingUsageInfo>,
pub unused_references: Vc<OptionBindingUsageInfo>,
pub minify: Vc<bool>, pub minify: Vc<bool>,
pub source_maps: Vc<SourceMapsType>, pub source_maps: Vc<SourceMapsType>,
pub no_mangling: Vc<bool>, pub no_mangling: Vc<bool>,
...@@ -1015,6 +1016,7 @@ pub async fn get_server_chunking_context_with_client_assets( ...@@ -1015,6 +1016,7 @@ pub async fn get_server_chunking_context_with_client_assets(
environment, environment,
module_id_strategy, module_id_strategy,
export_usage, export_usage,
unused_references,
minify, minify,
source_maps, source_maps,
no_mangling, no_mangling,
...@@ -1051,6 +1053,7 @@ pub async fn get_server_chunking_context_with_client_assets( ...@@ -1051,6 +1053,7 @@ pub async fn get_server_chunking_context_with_client_assets(
.source_maps(*source_maps.await?) .source_maps(*source_maps.await?)
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(*unused_references.await?)
.file_tracing(next_mode.is_production()) .file_tracing(next_mode.is_production())
.debug_ids(*debug_ids.await?) .debug_ids(*debug_ids.await?)
.nested_async_availability(*nested_async_chunking.await?); .nested_async_availability(*nested_async_chunking.await?);
...@@ -1097,6 +1100,7 @@ pub async fn get_server_chunking_context( ...@@ -1097,6 +1100,7 @@ pub async fn get_server_chunking_context(
environment, environment,
module_id_strategy, module_id_strategy,
export_usage, export_usage,
unused_references,
minify, minify,
source_maps, source_maps,
no_mangling, no_mangling,
...@@ -1133,6 +1137,7 @@ pub async fn get_server_chunking_context( ...@@ -1133,6 +1137,7 @@ pub async fn get_server_chunking_context(
.source_maps(*source_maps.await?) .source_maps(*source_maps.await?)
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(*unused_references.await?)
.file_tracing(next_mode.is_production()) .file_tracing(next_mode.is_production())
.debug_ids(*debug_ids.await?) .debug_ids(*debug_ids.await?)
.nested_async_availability(*nested_async_chunking.await?); .nested_async_availability(*nested_async_chunking.await?);
......
...@@ -300,6 +300,7 @@ export const experimentalSchema = { ...@@ -300,6 +300,7 @@ export const experimentalSchema = {
turbopackSourceMaps: z.boolean().optional(), turbopackSourceMaps: z.boolean().optional(),
turbopackInputSourceMaps: z.boolean().optional(), turbopackInputSourceMaps: z.boolean().optional(),
turbopackTreeShaking: z.boolean().optional(), turbopackTreeShaking: z.boolean().optional(),
turbopackRemoveUnusedImports: z.boolean().optional(),
turbopackRemoveUnusedExports: z.boolean().optional(), turbopackRemoveUnusedExports: z.boolean().optional(),
turbopackScopeHoisting: z.boolean().optional(), turbopackScopeHoisting: z.boolean().optional(),
turbopackClientSideNestedAsyncChunking: z.boolean().optional(), turbopackClientSideNestedAsyncChunking: z.boolean().optional(),
......
...@@ -452,6 +452,11 @@ export interface ExperimentalConfig { ...@@ -452,6 +452,11 @@ export interface ExperimentalConfig {
*/ */
turbopackTreeShaking?: boolean turbopackTreeShaking?: boolean
/**
* Enable removing unused imports for turbopack dev server and build.
*/
turbopackRemoveUnusedImports?: boolean
/** /**
* Enable removing unused exports for turbopack dev server and build. * Enable removing unused exports for turbopack dev server and build.
*/ */
......
export default function Root({ children }) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
import { Server } from '../library/index.js'
export default function page() {
return <Server />
}
export function Bar() {
async function create() {
'use server'
console.log('Action called')
}
return <button onClick={create}>Bar</button>
}
'use client'
export function Foo() {
return 'Client'
}
export function Server() {
return 'This is Server'
}
import { Foo } from './client.js'
// This is unused
export function Client() {
return <Foo />
}
import { Bar } from './action.js'
// This is unused
export function Action() {
return <Bar />
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('reference-tree-shaking', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('Should apply removeUnusedImports tree shaking to client and server references', async () => {
const res = await next.fetch('/')
expect(await res.text()).toContain('This is Server')
// Only Turbopack applies inner graph tree shaking here
if (process.env.IS_TURBOPACK_TEST) {
const serverReferences = await next.readFile(
'.next/server/server-reference-manifest.json'
)
expect(serverReferences).not.toContain('library/action.js')
const clientReferences = await next.readFile(
'.next/server/app/page_client-reference-manifest.js'
)
expect(clientReferences).not.toContain('library/client.js')
}
})
})
import React from 'react'
export default function Layout({ children }) {
return (
<html>
<head>
<title>My App</title>
</head>
<body>{children}</body>
</html>
)
}
'use client'
import { used } from '../library'
export default function Page() {
return <h1>My Page{used()}</h1>
}
export function a() {
return `This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
`
}
module.exports.b = function b() {
return `This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
`
}
import { b } from './b'
export function unused() {
return b()
}
export function used() {
return 'used'
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('remove-unused-imports', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should remove unused imports', async () => {
const browser = await next.browser('/')
let scripts = await browser.elementsByCss('script[src]')
expect(
(
await Promise.all(
scripts.map(async (el) => {
const src = await el.getAttribute('src')
const res = await next.fetch(src)
const code = await res.text()
if (code.includes('This is a big library.')) {
return src
}
return false
})
)
).filter((item) => item)
).toBeEmpty()
})
})
...@@ -23,10 +23,11 @@ use turbopack_core::{ ...@@ -23,10 +23,11 @@ use turbopack_core::{
module::Module, module::Module,
module_graph::{ module_graph::{
ModuleGraph, ModuleGraph,
binding_usage_info::{BindingUsageInfo, ModuleExportUsage},
chunk_group_info::ChunkGroup, chunk_group_info::ChunkGroup,
export_usage::{ExportUsageInfo, ModuleExportUsage},
}, },
output::{OutputAsset, OutputAssets}, output::{OutputAsset, OutputAssets},
reference::ModuleReference,
}; };
use turbopack_ecmascript::{ use turbopack_ecmascript::{
async_chunk::module::AsyncLoaderModule, async_chunk::module::AsyncLoaderModule,
...@@ -168,11 +169,19 @@ impl BrowserChunkingContextBuilder { ...@@ -168,11 +169,19 @@ impl BrowserChunkingContextBuilder {
self self
} }
pub fn export_usage(mut self, export_usage: Option<ResolvedVc<ExportUsageInfo>>) -> Self { pub fn export_usage(mut self, export_usage: Option<ResolvedVc<BindingUsageInfo>>) -> Self {
self.chunking_context.export_usage = export_usage; self.chunking_context.export_usage = export_usage;
self self
} }
pub fn unused_references(
mut self,
unused_references: Option<ResolvedVc<BindingUsageInfo>>,
) -> Self {
self.chunking_context.unused_references = unused_references;
self
}
pub fn debug_ids(mut self, debug_ids: bool) -> Self { pub fn debug_ids(mut self, debug_ids: bool) -> Self {
self.chunking_context.debug_ids = debug_ids; self.chunking_context.debug_ids = debug_ids;
self self
...@@ -291,7 +300,9 @@ pub struct BrowserChunkingContext { ...@@ -291,7 +300,9 @@ pub struct BrowserChunkingContext {
/// The module id strategy to use /// The module id strategy to use
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>, module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
/// The module export usage info, if available. /// The module export usage info, if available.
export_usage: Option<ResolvedVc<ExportUsageInfo>>, export_usage: Option<ResolvedVc<BindingUsageInfo>>,
/// Which references are unused and should be skipped (e.g. during codegen).
unused_references: Option<ResolvedVc<BindingUsageInfo>>,
/// The chunking configs /// The chunking configs
chunking_configs: Vec<(ResolvedVc<Box<dyn ChunkType>>, ChunkingConfig)>, chunking_configs: Vec<(ResolvedVc<Box<dyn ChunkType>>, ChunkingConfig)>,
/// Whether to use absolute URLs for static assets (e.g. in CSS: `url("/absolute/path")`) /// Whether to use absolute URLs for static assets (e.g. in CSS: `url("/absolute/path")`)
...@@ -340,6 +351,7 @@ impl BrowserChunkingContext { ...@@ -340,6 +351,7 @@ impl BrowserChunkingContext {
manifest_chunks: false, manifest_chunks: false,
module_id_strategy: ResolvedVc::upcast(DevModuleIdStrategy::new_resolved()), module_id_strategy: ResolvedVc::upcast(DevModuleIdStrategy::new_resolved()),
export_usage: None, export_usage: None,
unused_references: None,
chunking_configs: Default::default(), chunking_configs: Default::default(),
should_use_absolute_url_references: false, should_use_absolute_url_references: false,
}, },
...@@ -866,12 +878,24 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -866,12 +878,24 @@ impl ChunkingContext for BrowserChunkingContext {
if let Some(export_usage) = self.await?.export_usage { if let Some(export_usage) = self.await?.export_usage {
Ok(export_usage.await?.used_exports(module).await?) Ok(export_usage.await?.used_exports(module).await?)
} else { } else {
// In development mode, we don't have export usage info, so we assume all exports are
// used.
Ok(ModuleExportUsage::all()) Ok(ModuleExportUsage::all())
} }
} }
#[turbo_tasks::function]
async fn is_reference_unused(
self: Vc<Self>,
reference: ResolvedVc<Box<dyn ModuleReference>>,
) -> Result<Vc<bool>> {
if let Some(unused_references) = self.await?.unused_references {
Ok(Vc::cell(
unused_references.await?.is_reference_unused(&reference),
))
} else {
Ok(Vc::cell(false))
}
}
#[turbo_tasks::function] #[turbo_tasks::function]
async fn debug_ids_enabled(self: Vc<Self>) -> Result<Vc<bool>> { async fn debug_ids_enabled(self: Vc<Self>) -> Result<Vc<bool>> {
Ok(Vc::cell(self.await?.debug_ids)) Ok(Vc::cell(self.await?.debug_ids))
......
...@@ -33,8 +33,8 @@ use turbopack_core::{ ...@@ -33,8 +33,8 @@ use turbopack_core::{
module::Module, module::Module,
module_graph::{ module_graph::{
ModuleGraph, ModuleGraph,
binding_usage_info::compute_binding_usage_info,
chunk_group_info::{ChunkGroup, ChunkGroupEntry}, chunk_group_info::{ChunkGroup, ChunkGroupEntry},
export_usage::compute_export_usage_info,
}, },
output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced}, output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced},
reference_type::{EntryReferenceSubType, ReferenceType}, reference_type::{EntryReferenceSubType, ReferenceType},
...@@ -305,7 +305,7 @@ async fn build_internal( ...@@ -305,7 +305,7 @@ async fn build_internal(
.instrument(tracing::info_span!("resolve entries")) .instrument(tracing::info_span!("resolve entries"))
.await?; .await?;
let module_graph = ModuleGraph::from_modules( let mut module_graph = ModuleGraph::from_modules(
Vc::cell(vec![ChunkGroupEntry::Entry(entries.clone())]), Vc::cell(vec![ChunkGroupEntry::Entry(entries.clone())]),
false, false,
); );
...@@ -314,9 +314,10 @@ async fn build_internal( ...@@ -314,9 +314,10 @@ async fn build_internal(
.to_resolved() .to_resolved()
.await?, .await?,
); );
let export_usage = compute_export_usage_info(module_graph.to_resolved().await?) let binding_usage = compute_binding_usage_info(module_graph.to_resolved().await?, true)
.resolve_strongly_consistent() .resolve_strongly_consistent()
.await?; .await?;
module_graph = module_graph.without_unused_references(*binding_usage);
let chunking_context: Vc<Box<dyn ChunkingContext>> = match target { let chunking_context: Vc<Box<dyn ChunkingContext>> = match target {
Target::Browser => { Target::Browser => {
...@@ -342,7 +343,8 @@ async fn build_internal( ...@@ -342,7 +343,8 @@ async fn build_internal(
) )
.source_maps(source_maps_type) .source_maps(source_maps_type)
.module_id_strategy(module_id_strategy) .module_id_strategy(module_id_strategy)
.export_usage(Some(export_usage)) .export_usage(Some(binding_usage))
.unused_references(Some(binding_usage))
.current_chunk_method(CurrentChunkMethod::DocumentCurrentScript) .current_chunk_method(CurrentChunkMethod::DocumentCurrentScript)
.minify_type(minify_type); .minify_type(minify_type);
...@@ -391,7 +393,8 @@ async fn build_internal( ...@@ -391,7 +393,8 @@ async fn build_internal(
) )
.source_maps(source_maps_type) .source_maps(source_maps_type)
.module_id_strategy(module_id_strategy) .module_id_strategy(module_id_strategy)
.export_usage(Some(export_usage)) .export_usage(Some(binding_usage))
.unused_references(Some(binding_usage))
.minify_type(minify_type); .minify_type(minify_type);
match *node_env.await? { match *node_env.await? {
......
...@@ -14,13 +14,14 @@ use crate::{ ...@@ -14,13 +14,14 @@ use crate::{
ident::AssetIdent, ident::AssetIdent,
module::Module, module::Module,
module_graph::{ module_graph::{
ModuleGraph, chunk_group_info::ChunkGroup, export_usage::ModuleExportUsage, ModuleGraph, binding_usage_info::ModuleExportUsage, chunk_group_info::ChunkGroup,
module_batches::BatchingConfig, module_batches::BatchingConfig,
}, },
output::{ output::{
ExpandOutputAssetsInput, OutputAsset, OutputAssets, OutputAssetsReferences, ExpandOutputAssetsInput, OutputAsset, OutputAssets, OutputAssetsReferences,
OutputAssetsWithReferenced, expand_output_assets, OutputAssetsWithReferenced, expand_output_assets,
}, },
reference::ModuleReference,
}; };
#[derive( #[derive(
...@@ -439,6 +440,12 @@ pub trait ChunkingContext { ...@@ -439,6 +440,12 @@ pub trait ChunkingContext {
module: Vc<Box<dyn Module>>, module: Vc<Box<dyn Module>>,
) -> Result<Vc<ModuleExportUsage>>; ) -> Result<Vc<ModuleExportUsage>>;
#[turbo_tasks::function]
async fn is_reference_unused(
self: Vc<Self>,
reference: Vc<Box<dyn ModuleReference>>,
) -> Result<Vc<bool>>;
/// Returns whether debug IDs are enabled for this chunking context. /// Returns whether debug IDs are enabled for this chunking context.
#[turbo_tasks::function] #[turbo_tasks::function]
fn debug_ids_enabled(self: Vc<Self>) -> Vc<bool>; fn debug_ids_enabled(self: Vc<Self>) -> Vc<bool>;
......
...@@ -46,7 +46,7 @@ use crate::{ ...@@ -46,7 +46,7 @@ use crate::{
}, },
output::{OutputAssets, OutputAssetsReference}, output::{OutputAssets, OutputAssetsReference},
reference::ModuleReference, reference::ModuleReference,
resolve::ExportUsage, resolve::BindingUsage,
}; };
/// A module id, which can be a number or string /// A module id, which can be a number or string
...@@ -416,8 +416,8 @@ pub trait ChunkableModuleReference: ModuleReference + ValueToString { ...@@ -416,8 +416,8 @@ pub trait ChunkableModuleReference: ModuleReference + ValueToString {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn export_usage(self: Vc<Self>) -> Vc<ExportUsage> { fn binding_usage(self: Vc<Self>) -> Vc<BindingUsage> {
ExportUsage::all() BindingUsage::all()
} }
} }
......
...@@ -4,7 +4,7 @@ use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc}; ...@@ -4,7 +4,7 @@ use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc};
use crate::{ use crate::{
module::{Module, Modules}, module::{Module, Modules},
module_graph::{GraphTraversalAction, ModuleGraph, SingleModuleGraph}, module_graph::{GraphTraversalAction, ModuleGraph, SingleModuleGraphWithBindingUsage},
}; };
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
...@@ -37,25 +37,29 @@ impl AsyncModulesInfo { ...@@ -37,25 +37,29 @@ impl AsyncModulesInfo {
#[turbo_tasks::function(operation)] #[turbo_tasks::function(operation)]
pub async fn compute_async_module_info( pub async fn compute_async_module_info(
graph: ResolvedVc<ModuleGraph>, graphs: ResolvedVc<ModuleGraph>,
) -> Result<Vc<AsyncModulesInfo>> { ) -> Result<Vc<AsyncModulesInfo>> {
// Layout segment optimization, we can individually compute the async modules for each graph. // Layout segment optimization, we can individually compute the async modules for each graph.
let mut result: Vc<AsyncModulesInfo> = Vc::cell(Default::default()); let mut result: Vc<AsyncModulesInfo> = Vc::cell(Default::default());
for g in &graph.await?.graphs { let graphs = graphs.await?;
result = compute_async_module_info_single(**g, result); for graph in graphs.iter_graphs() {
result = compute_async_module_info_single(graph, result);
} }
Ok(result) Ok(result)
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn compute_async_module_info_single( async fn compute_async_module_info_single(
graph: Vc<SingleModuleGraph>, graph: SingleModuleGraphWithBindingUsage,
parent_async_modules: Vc<AsyncModulesInfo>, parent_async_modules: Vc<AsyncModulesInfo>,
) -> Result<Vc<AsyncModulesInfo>> { ) -> Result<Vc<AsyncModulesInfo>> {
let parent_async_modules = parent_async_modules.await?; let parent_async_modules = parent_async_modules.await?;
let graph = graph.await?; let graph = graph.read().await?;
let self_async_modules = graph let self_async_modules = graph
.graphs
.first()
.unwrap()
.iter_nodes() .iter_nodes()
.map(async |node| Ok((node, *node.is_self_async().await?))) .map(async |node| Ok((node, *node.is_self_async().await?)))
.try_join() .try_join()
...@@ -73,9 +77,8 @@ async fn compute_async_module_info_single( ...@@ -73,9 +77,8 @@ async fn compute_async_module_info_single(
// modules in the SCC is async. // modules in the SCC is async.
let mut async_modules = self_async_modules; let mut async_modules = self_async_modules;
let graph_ref = graph.read(); graph.traverse_edges_from_entries_dfs(
graph_ref.traverse_edges_from_entries_dfs( graph.graphs.first().unwrap().entry_modules(),
graph.entry_modules(),
&mut (), &mut (),
|_, _, _| Ok(GraphTraversalAction::Continue), |_, _, _| Ok(GraphTraversalAction::Continue),
|parent_info, module, _| { |parent_info, module, _| {
...@@ -91,7 +94,7 @@ async fn compute_async_module_info_single( ...@@ -91,7 +94,7 @@ async fn compute_async_module_info_single(
}, },
)?; )?;
graph_ref.traverse_cycles( graph.traverse_cycles(
|ref_data| ref_data.chunking_type.is_inherit_async(), |ref_data| ref_data.chunking_type.is_inherit_async(),
|cycle| { |cycle| {
if cycle.iter().any(|node| async_modules.contains(node)) { if cycle.iter().any(|node| async_modules.contains(node)) {
......
...@@ -507,7 +507,7 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraphRef) -> Result<Vc<Chunk ...@@ -507,7 +507,7 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraphRef) -> Result<Vc<Chunk
}) })
.collect::<Result<Vec<_>>>()?, .collect::<Result<Vec<_>>>()?,
&mut module_chunk_groups, &mut module_chunk_groups,
|parent_info: Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>, |parent_info: Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData, _)>,
node: ResolvedVc<Box<dyn Module>>, node: ResolvedVc<Box<dyn Module>>,
module_chunk_groups: &mut FxHashMap< module_chunk_groups: &mut FxHashMap<
ResolvedVc<Box<dyn Module>>, ResolvedVc<Box<dyn Module>>,
...@@ -518,7 +518,7 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraphRef) -> Result<Vc<Chunk ...@@ -518,7 +518,7 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraphRef) -> Result<Vc<Chunk
Inherit(ResolvedVc<Box<dyn Module>>), Inherit(ResolvedVc<Box<dyn Module>>),
ChunkGroup(It), ChunkGroup(It),
} }
let chunk_groups = if let Some((parent, ref_data)) = parent_info { let chunk_groups = if let Some((parent, ref_data, _)) = parent_info {
match &ref_data.chunking_type { match &ref_data.chunking_type {
ChunkingType::Parallel { .. } => ChunkGroupInheritance::Inherit(parent), ChunkingType::Parallel { .. } => ChunkGroupInheritance::Inherit(parent),
ChunkingType::Async => ChunkGroupInheritance::ChunkGroup(Either::Left( ChunkingType::Async => ChunkGroupInheritance::ChunkGroup(Either::Left(
......
//! Intermediate tree shaking that uses global information but not good as the full tree shaking.
use anyhow::Result;
use auto_hash_map::AutoSet;
use rustc_hash::{FxHashMap, FxHashSet};
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc};
use crate::{module::Module, module_graph::ModuleGraph, resolve::ExportUsage};
#[turbo_tasks::function(operation)]
pub async fn compute_export_usage_info(
graph: ResolvedVc<ModuleGraph>,
) -> Result<Vc<ExportUsageInfo>> {
let mut used_exports = FxHashMap::<_, ModuleExportUsageInfo>::default();
let graph = graph.read_graphs().await?;
graph.traverse_all_edges_unordered(|(_, ref_data), target| {
let e = used_exports.entry(target).or_default();
e.add(&ref_data.export);
Ok(())
})?;
// Compute cycles and select modules to be 'circuit breakers'
// A circuit breaker module will need to eagerly export lazy getters for its exports to break an
// evaluation cycle all other modules can export values after defining them
let mut circuit_breakers = FxHashSet::default();
graph.traverse_cycles(
|e| e.chunking_type.is_parallel(),
|cycle| {
// To break cycles we need to ensure that no importing module can observe a
// partially populated exports object.
// We could compute this based on the module graph via a DFS from each entry point
// to the cycle. Whatever node is hit first is an entry point to the cycle.
// (scope hoisting does something similar) and then we would only need to
// mark 'entry' modules (basically the targets of back edges in the export graph) as
// circuit breakers. For now we just mark everything on the theory that cycles are
// rare. For vercel-site on 8/22/2025 there were 106 cycles covering 800 modules
// (or 1.2% of all modules). So with this analysis we could potentially drop 80% of
// the cycle breaker modules.
circuit_breakers.extend(cycle.iter().map(|n| **n));
Ok(())
},
)?;
Ok(ExportUsageInfo {
used_exports,
circuit_breakers,
}
.cell())
}
#[turbo_tasks::value(transparent)]
pub struct OptionExportUsageInfo(Option<ResolvedVc<ExportUsageInfo>>);
#[turbo_tasks::value]
pub struct ExportUsageInfo {
used_exports: FxHashMap<ResolvedVc<Box<dyn Module>>, ModuleExportUsageInfo>,
circuit_breakers: FxHashSet<ResolvedVc<Box<dyn Module>>>,
}
#[turbo_tasks::value(shared)]
pub struct ModuleExportUsage {
pub export_usage: ResolvedVc<ModuleExportUsageInfo>,
// Whether this module exists in an import cycle and has been selected to break the cycle.
pub is_circuit_breaker: bool,
}
#[turbo_tasks::value_impl]
impl ModuleExportUsage {
#[turbo_tasks::function]
pub async fn all() -> Result<Vc<Self>> {
Ok(Self {
export_usage: ModuleExportUsageInfo::all().to_resolved().await?,
is_circuit_breaker: true,
}
.cell())
}
}
impl ExportUsageInfo {
pub async fn used_exports(
&self,
module: ResolvedVc<Box<dyn Module>>,
) -> Result<Vc<ModuleExportUsage>> {
let is_circuit_breaker = self.circuit_breakers.contains(&module);
let export_usage = if let Some(exports) = self.used_exports.get(&module) {
exports.clone().resolved_cell()
} else {
// We exclude template files from tree shaking because they are entrypoints to the
// module graph.
ModuleExportUsageInfo::all().to_resolved().await?
};
Ok(ModuleExportUsage {
export_usage,
is_circuit_breaker,
}
.cell())
}
}
#[turbo_tasks::value]
#[derive(Default, Clone)]
pub enum ModuleExportUsageInfo {
/// Only the side effects are needed, no exports is used.
#[default]
Evaluation,
Exports(AutoSet<RcStr>),
All,
}
#[turbo_tasks::value_impl]
impl ModuleExportUsageInfo {
#[turbo_tasks::function]
pub fn all() -> Vc<Self> {
ModuleExportUsageInfo::All.cell()
}
}
impl ModuleExportUsageInfo {
fn add(&mut self, usage: &ExportUsage) {
match (&mut *self, usage) {
(Self::All, _) => {}
(_, ExportUsage::All) => {
*self = Self::All;
}
(Self::Evaluation, ExportUsage::Named(name)) => {
// Promote evaluation to something more specific
*self = Self::Exports(AutoSet::from_iter([name.clone()]));
}
(Self::Exports(l), ExportUsage::Named(r)) => {
// Merge exports
l.insert(r.clone());
}
(_, ExportUsage::Evaluation) => {
// Ignore evaluation
}
}
}
pub fn is_export_used(&self, export: &RcStr) -> bool {
match self {
Self::All => true,
Self::Evaluation => false,
Self::Exports(exports) => exports.contains(export),
}
}
}
...@@ -148,21 +148,22 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc< ...@@ -148,21 +148,22 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc<
.map(|e| Ok((*e, -*module_depth.get(e).context("Module depth not found")?))) .map(|e| Ok((*e, -*module_depth.get(e).context("Module depth not found")?)))
.collect::<Result<Vec<_>>>()?, .collect::<Result<Vec<_>>>()?,
&mut (), &mut (),
|parent_info: Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>, |parent_info: Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData, _)>,
node: ResolvedVc<Box<dyn Module>>, node: ResolvedVc<Box<dyn Module>>,
_| _|
-> Result<GraphTraversalAction> { -> Result<GraphTraversalAction> {
// On the down traversal, establish which edges are mergeable and set the list // On the down traversal, establish which edges are mergeable and set the list
// indices. // indices.
let (parent_module, hoisted) = parent_info.map_or((None, false), |(node, ty)| { let (parent_module, hoisted) =
( parent_info.map_or((None, false), |(node, ty, _)| {
Some(node), (
match &ty.chunking_type { Some(node),
ChunkingType::Parallel { hoisted, .. } => *hoisted, match &ty.chunking_type {
_ => false, ChunkingType::Parallel { hoisted, .. } => *hoisted,
}, _ => false,
) },
}); )
});
let module = node; let module = node;
Ok(if parent_module.is_some_and(|p| p == module) { Ok(if parent_module.is_some_and(|p| p == module) {
...@@ -490,7 +491,9 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc< ...@@ -490,7 +491,9 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc<
// necessarily needed for browser), // necessarily needed for browser),
exposed_modules_imported.insert(module); exposed_modules_imported.insert(module);
} }
if parent_info.is_some_and(|(_, r)| matches!(r.export, ExportUsage::All)) { if parent_info
.is_some_and(|(_, r)| matches!(r.binding_usage.export, ExportUsage::All))
{
// This module needs to be exposed: // This module needs to be exposed:
// - namespace import from another group // - namespace import from another group
exposed_modules_namespace.insert(module); exposed_modules_namespace.insert(module);
......
...@@ -350,28 +350,30 @@ pub async fn compute_module_batches( ...@@ -350,28 +350,30 @@ pub async fn compute_module_batches(
// Walk the module graph and mark all modules that are boundary modules (referenced from a // Walk the module graph and mark all modules that are boundary modules (referenced from a
// different chunk group bitmap) // different chunk group bitmap)
module_graph.traverse_all_edges_unordered(|(parent, ty), node| { module_graph.traverse_all_edges_unordered(|parent, node| {
let std::collections::hash_set::Entry::Vacant(entry) = if let Some((parent, ty)) = parent {
pre_batches.boundary_modules.entry(node) let std::collections::hash_set::Entry::Vacant(entry) =
else { pre_batches.boundary_modules.entry(node)
// Already a boundary module, can skip check else {
return Ok(()); // Already a boundary module, can skip check
}; return Ok(());
if ty.chunking_type.is_parallel() { };
let parent_chunk_groups = chunk_group_info if ty.chunking_type.is_parallel() {
.module_chunk_groups let parent_chunk_groups = chunk_group_info
.get(&parent) .module_chunk_groups
.context("all modules need to have chunk group info")?; .get(&parent)
let chunk_groups = chunk_group_info .context("all modules need to have chunk group info")?;
.module_chunk_groups let chunk_groups = chunk_group_info
.get(&node) .module_chunk_groups
.context("all modules need to have chunk group info")?; .get(&node)
if parent_chunk_groups != chunk_groups { .context("all modules need to have chunk group info")?;
// This is a boundary module if parent_chunk_groups != chunk_groups {
// This is a boundary module
entry.insert();
}
} else {
entry.insert(); entry.insert();
} }
} else {
entry.insert();
} }
Ok(()) Ok(())
})?; })?;
......
use std::collections::HashSet; use std::collections::HashSet;
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ use turbo_tasks::{
FxIndexSet, ReadRef, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, ValueToString, Vc, FxIndexSet, NonLocalValue, ReadRef, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt,
ValueToString, Vc, debug::ValueDebugFormat, trace::TraceRawVcs,
}; };
use crate::{ use crate::{
...@@ -14,7 +16,7 @@ use crate::{ ...@@ -14,7 +16,7 @@ use crate::{
expand_output_assets, expand_output_assets,
}, },
raw_module::RawModule, raw_module::RawModule,
resolve::{ExportUsage, ModuleResolveResult, RequestKey}, resolve::{BindingUsage, ExportUsage, ImportUsage, ModuleResolveResult, RequestKey},
}; };
pub mod source_map; pub mod source_map;
...@@ -121,8 +123,12 @@ impl ChunkableModuleReference for SingleChunkableModuleReference { ...@@ -121,8 +123,12 @@ impl ChunkableModuleReference for SingleChunkableModuleReference {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn export_usage(&self) -> Vc<ExportUsage> { async fn binding_usage(&self) -> Result<Vc<BindingUsage>> {
*self.export Ok(BindingUsage {
import: ImportUsage::SideEffects,
export: self.export.owned().await?,
}
.cell())
} }
} }
...@@ -287,8 +293,17 @@ pub async fn primary_referenced_modules(module: Vc<Box<dyn Module>>) -> Result<V ...@@ -287,8 +293,17 @@ pub async fn primary_referenced_modules(module: Vc<Box<dyn Module>>) -> Result<V
Ok(Vc::cell(modules)) Ok(Vc::cell(modules))
} }
#[derive(
Clone, Serialize, Deserialize, Eq, PartialEq, ValueDebugFormat, TraceRawVcs, NonLocalValue,
)]
pub struct ResolvedReference {
pub chunking_type: ChunkingType,
pub binding_usage: BindingUsage,
pub modules: ReadRef<Modules>,
}
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct ModulesWithRefData(Vec<(ChunkingType, ExportUsage, ReadRef<Modules>)>); pub struct ModulesWithRefData(Vec<(ResolvedVc<Box<dyn ModuleReference>>, ResolvedReference)>);
/// Aggregates all primary [Module]s referenced by an [Module] via [ChunkableModuleReference]s. /// Aggregates all primary [Module]s referenced by an [Module] via [ChunkableModuleReference]s.
/// This does not include transitively referenced [Module]s, only includes /// This does not include transitively referenced [Module]s, only includes
...@@ -319,9 +334,16 @@ pub async fn primary_chunkable_referenced_modules( ...@@ -319,9 +334,16 @@ pub async fn primary_chunkable_referenced_modules(
.await? .await?
.primary_modules() .primary_modules()
.await?; .await?;
let export = reference.export_usage().owned().await?; let binding_usage = reference.binding_usage().owned().await?;
return Ok(Some((chunking_type.clone(), export, resolved))); return Ok(Some((
ResolvedVc::upcast(reference),
ResolvedReference {
chunking_type: chunking_type.clone(),
binding_usage,
modules: resolved,
},
)));
} }
Ok(None) Ok(None)
}) })
......
...@@ -7,6 +7,7 @@ use std::{ ...@@ -7,6 +7,7 @@ use std::{
}; };
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use auto_hash_map::AutoSet;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::{Instrument, Level}; use tracing::{Instrument, Level};
...@@ -103,6 +104,35 @@ impl ModuleResolveResultItem { ...@@ -103,6 +104,35 @@ impl ModuleResolveResultItem {
} }
} }
#[turbo_tasks::value(shared)]
#[derive(Clone, Debug, Hash, Default)]
pub struct BindingUsage {
pub import: ImportUsage,
pub export: ExportUsage,
}
#[turbo_tasks::value_impl]
impl BindingUsage {
#[turbo_tasks::function]
pub fn all() -> Vc<Self> {
Self::default().cell()
}
}
#[turbo_tasks::value(shared)]
#[derive(Debug, Clone, Default, Hash)]
pub enum ImportUsage {
/// This import is used by some side effect in the module (and can't be tree shaken).
#[default]
SideEffects,
/// This import is used only by these specific exports, if all exports are unused, the import
/// can also be removed.
///
/// (This is only ever set on `ModulePart::Export` references. Side effects are handled via
/// `ModulePart::Evaluation` references, which always have `ImportUsage::SideEffects`.)
Exports(AutoSet<RcStr>),
}
#[turbo_tasks::value] #[turbo_tasks::value]
#[derive(Debug, Clone, Default, Hash)] #[derive(Debug, Clone, Default, Hash)]
pub enum ExportUsage { pub enum ExportUsage {
......
...@@ -31,7 +31,7 @@ use super::{ ...@@ -31,7 +31,7 @@ use super::{
use crate::{ use crate::{
AnalyzeMode, SpecifiedModuleType, AnalyzeMode, SpecifiedModuleType,
analyzer::{WellKnownObjectKind, is_unresolved}, analyzer::{WellKnownObjectKind, is_unresolved},
references::constant_value::parse_single_expr_lit, references::{constant_value::parse_single_expr_lit, for_each_ident_in_pat},
utils::{AstPathRange, unparen}, utils::{AstPathRange, unparen},
}; };
...@@ -307,6 +307,30 @@ impl VarMeta { ...@@ -307,6 +307,30 @@ impl VarMeta {
} }
} }
#[derive(Clone, Debug)]
pub enum DeclUsage {
SideEffects,
Bindings(FxHashSet<Id>),
}
impl Default for DeclUsage {
fn default() -> Self {
DeclUsage::Bindings(Default::default())
}
}
impl DeclUsage {
fn add_usage(&mut self, user: &Id) {
match self {
Self::Bindings(set) => {
set.insert(user.clone());
}
Self::SideEffects => {}
}
}
fn make_side_effects(&mut self) {
*self = Self::SideEffects;
}
}
#[derive(Debug)] #[derive(Debug)]
pub struct VarGraph { pub struct VarGraph {
pub values: FxHashMap<Id, VarMeta>, pub values: FxHashMap<Id, VarMeta>,
...@@ -315,6 +339,13 @@ pub struct VarGraph { ...@@ -315,6 +339,13 @@ pub struct VarGraph {
pub free_var_ids: FxHashMap<Atom, Id>, pub free_var_ids: FxHashMap<Atom, Id>,
pub effects: Vec<Effect>, pub effects: Vec<Effect>,
// ident -> immediate usage (top level decl)
pub decl_usages: FxHashMap<Id, DeclUsage>,
// import -> immediate usage (top level decl)
pub import_usages: FxHashMap<usize, DeclUsage>,
// export name -> top level decl
pub exports: FxHashMap<Atom, Id>,
} }
impl VarGraph { impl VarGraph {
...@@ -339,14 +370,17 @@ pub fn create_graph( ...@@ -339,14 +370,17 @@ pub fn create_graph(
values: Default::default(), values: Default::default(),
free_var_ids: Default::default(), free_var_ids: Default::default(),
effects: Default::default(), effects: Default::default(),
decl_usages: Default::default(),
import_usages: Default::default(),
exports: Default::default(),
}; };
m.visit_with_ast_path( m.visit_with_ast_path(
&mut Analyzer { &mut Analyzer {
analyze_mode, analyze_mode,
data: &mut graph, data: &mut graph,
state: analyzer_state::AnalyzerState::new(),
eval_context, eval_context,
state: Default::default(),
effects: Default::default(), effects: Default::default(),
hoisted_effects: Default::default(), hoisted_effects: Default::default(),
}, },
...@@ -873,9 +907,9 @@ struct Analyzer<'a> { ...@@ -873,9 +907,9 @@ struct Analyzer<'a> {
state: analyzer_state::AnalyzerState, state: analyzer_state::AnalyzerState,
effects: Vec<Effect>, effects: Vec<Effect>,
// Effects collected from hoisted declarations. See https://developer.mozilla.org/en-US/docs/Glossary/Hoisting /// Effects collected from hoisted declarations. See https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
// Tracked separately so we can preserve effects from hoisted declarations even when we don't /// Tracked separately so we can preserve effects from hoisted declarations even when we don't
// collect effects from the declaring context. /// collect effects from the declaring context.
hoisted_effects: Vec<Effect>, hoisted_effects: Vec<Effect>,
eval_context: &'a EvalContext, eval_context: &'a EvalContext,
...@@ -956,6 +990,7 @@ mod analyzer_state { ...@@ -956,6 +990,7 @@ mod analyzer_state {
/// Contains fields of `Analyzer` that should only be modified using helper methods. These are /// Contains fields of `Analyzer` that should only be modified using helper methods. These are
/// intentionally private to the rest of the `Analyzer` implementation. /// intentionally private to the rest of the `Analyzer` implementation.
#[derive(Default)]
pub struct AnalyzerState { pub struct AnalyzerState {
pat_value: Option<JsValue>, pat_value: Option<JsValue>,
/// Return values of the current function. /// Return values of the current function.
...@@ -967,17 +1002,14 @@ mod analyzer_state { ...@@ -967,17 +1002,14 @@ mod analyzer_state {
early_return_stack: Vec<EarlyReturn>, early_return_stack: Vec<EarlyReturn>,
lexical_stack: Vec<LexicalContext>, lexical_stack: Vec<LexicalContext>,
var_decl_kind: Option<VarDeclKind>, var_decl_kind: Option<VarDeclKind>,
cur_top_level_decl_name: Option<Id>,
} }
impl AnalyzerState { impl AnalyzerState {
pub fn new() -> AnalyzerState { /// Returns the identifier of the current top level declaration.
AnalyzerState { pub(super) fn cur_top_level_decl_name(&self) -> &Option<Id> {
pat_value: None, &self.cur_top_level_decl_name
cur_fn_return_values: None,
early_return_stack: Default::default(),
lexical_stack: Default::default(),
var_decl_kind: None,
}
} }
} }
...@@ -1273,6 +1305,23 @@ mod analyzer_state { ...@@ -1273,6 +1305,23 @@ mod analyzer_state {
} }
always_returns always_returns
} }
/// Runs `visitor` with the current top level declaration identifier
pub(super) fn enter_top_level_decl<T>(
&mut self,
name: &Ident,
visitor: impl FnOnce(&mut Self) -> T,
) -> T {
let is_top_level_fn = self.state.cur_top_level_decl_name.is_none();
if is_top_level_fn {
self.state.cur_top_level_decl_name = Some(name.to_id());
}
let result = visitor(self);
if is_top_level_fn {
self.state.cur_top_level_decl_name = None;
}
result
}
} }
} }
...@@ -1909,9 +1958,12 @@ impl VisitAstPath for Analyzer<'_> { ...@@ -1909,9 +1958,12 @@ impl VisitAstPath for Analyzer<'_> {
decl: &'ast FnDecl, decl: &'ast FnDecl,
ast_path: &mut AstNodePath<AstParentNodeRef<'r>>, ast_path: &mut AstNodePath<AstParentNodeRef<'r>>,
) { ) {
let fn_value = self.enter_fn(&*decl.function, |this| { let fn_value = self.enter_top_level_decl(&decl.ident, |this| {
decl.visit_children_with_ast_path(this, ast_path); this.enter_fn(&*decl.function, |this| {
decl.visit_children_with_ast_path(this, ast_path);
})
}); });
// Take all effects produced by the function and move them to hoisted effects since // Take all effects produced by the function and move them to hoisted effects since
// function declarations are hoisted. // function declarations are hoisted.
// This accounts for the fact that even with `if (true) { return f} function f() {} ` `f` is // This accounts for the fact that even with `if (true) { return f} function f() {} ` `f` is
...@@ -2386,6 +2438,17 @@ impl VisitAstPath for Analyzer<'_> { ...@@ -2386,6 +2438,17 @@ impl VisitAstPath for Analyzer<'_> {
if let Some((esm_reference_index, export)) = if let Some((esm_reference_index, export)) =
self.eval_context.imports.get_binding(&ident.to_id()) self.eval_context.imports.get_binding(&ident.to_id())
{ {
let usage = self
.data
.import_usages
.entry(esm_reference_index)
.or_default();
if let Some(top_level) = self.state.cur_top_level_decl_name() {
usage.add_usage(top_level);
} else {
usage.make_side_effects();
}
// Optimization: Look for a MemberExpr to see if we only access a few members from the // Optimization: Look for a MemberExpr to see if we only access a few members from the
// module, add those specific effects instead of depending on the entire module. // module, add those specific effects instead of depending on the entire module.
// //
...@@ -2432,6 +2495,24 @@ impl VisitAstPath for Analyzer<'_> { ...@@ -2432,6 +2495,24 @@ impl VisitAstPath for Analyzer<'_> {
span: ident.span(), span: ident.span(),
}) })
} }
if !is_unresolved(ident, self.eval_context.unresolved_mark) {
if let Some(top_level) = self.state.cur_top_level_decl_name() {
if !(ident.sym == top_level.0 && ident.ctxt == top_level.1) {
self.data
.decl_usages
.entry(ident.to_id())
.or_default()
.add_usage(top_level);
}
} else {
self.data
.decl_usages
.entry(ident.to_id())
.or_default()
.make_side_effects();
}
}
} }
fn visit_this_expr<'ast: 'r, 'r>( fn visit_this_expr<'ast: 'r, 'r>(
...@@ -2728,6 +2809,55 @@ impl VisitAstPath for Analyzer<'_> { ...@@ -2728,6 +2809,55 @@ impl VisitAstPath for Analyzer<'_> {
self.effects = prev_effects; self.effects = prev_effects;
} }
fn visit_export_decl<'ast: 'r, 'r>(
&mut self,
node: &'ast ExportDecl,
ast_path: &mut swc_core::ecma::visit::AstNodePath<'r>,
) {
match &node.decl {
Decl::Class(node) => {
self.data
.exports
.insert(node.ident.sym.clone(), node.ident.to_id());
}
Decl::Fn(node) => {
self.data
.exports
.insert(node.ident.sym.clone(), node.ident.to_id());
}
Decl::Var(node) => {
for VarDeclarator { name, .. } in &node.decls {
for_each_ident_in_pat(name, &mut |name, ctxt| {
self.data.exports.insert(name.clone(), (name.clone(), ctxt));
});
}
}
_ => {}
};
node.visit_children_with_ast_path(self, ast_path);
}
fn visit_export_named_specifier<'ast: 'r, 'r>(
&mut self,
node: &'ast ExportNamedSpecifier,
ast_path: &mut swc_core::ecma::visit::AstNodePath<'r>,
) {
let export_name = node
.exported
.as_ref()
.unwrap_or(&node.orig)
.atom()
.into_owned();
self.data.exports.insert(
export_name,
match &node.orig {
ModuleExportName::Ident(ident) => ident.to_id(),
ModuleExportName::Str(_) => unreachable!("exporting a string should be impossible"),
},
);
node.visit_children_with_ast_path(self, ast_path);
}
} }
impl Analyzer<'_> { impl Analyzer<'_> {
......
...@@ -23,12 +23,12 @@ use turbopack_core::{ ...@@ -23,12 +23,12 @@ use turbopack_core::{
OptionStyledString, StyledString, OptionStyledString, StyledString,
}, },
module::Module, module::Module,
module_graph::export_usage::ModuleExportUsageInfo, module_graph::binding_usage_info::ModuleExportUsageInfo,
reference::ModuleReference, reference::ModuleReference,
reference_type::{EcmaScriptModulesReferenceSubType, ImportWithType}, reference_type::{EcmaScriptModulesReferenceSubType, ImportWithType},
resolve::{ resolve::{
ExportUsage, ExternalType, ModulePart, ModuleResolveResult, ModuleResolveResultItem, BindingUsage, ExportUsage, ExternalType, ImportUsage, ModulePart, ModuleResolveResult,
RequestKey, ModuleResolveResultItem, RequestKey,
origin::{ResolveOrigin, ResolveOriginExt}, origin::{ResolveOrigin, ResolveOriginExt},
parse::Request, parse::Request,
}, },
...@@ -325,6 +325,7 @@ pub struct EsmAssetReference { ...@@ -325,6 +325,7 @@ pub struct EsmAssetReference {
pub annotations: ImportAnnotations, pub annotations: ImportAnnotations,
pub issue_source: IssueSource, pub issue_source: IssueSource,
pub export_name: Option<ModulePart>, pub export_name: Option<ModulePart>,
pub import_usage: ImportUsage,
pub import_externals: bool, pub import_externals: bool,
pub is_pure_import: bool, pub is_pure_import: bool,
} }
...@@ -346,6 +347,7 @@ impl EsmAssetReference { ...@@ -346,6 +347,7 @@ impl EsmAssetReference {
issue_source: IssueSource, issue_source: IssueSource,
annotations: ImportAnnotations, annotations: ImportAnnotations,
export_name: Option<ModulePart>, export_name: Option<ModulePart>,
import_usage: ImportUsage,
import_externals: bool, import_externals: bool,
) -> Self { ) -> Self {
EsmAssetReference { EsmAssetReference {
...@@ -354,6 +356,7 @@ impl EsmAssetReference { ...@@ -354,6 +356,7 @@ impl EsmAssetReference {
issue_source, issue_source,
annotations, annotations,
export_name, export_name,
import_usage,
import_externals, import_externals,
is_pure_import: false, is_pure_import: false,
} }
...@@ -365,6 +368,7 @@ impl EsmAssetReference { ...@@ -365,6 +368,7 @@ impl EsmAssetReference {
issue_source: IssueSource, issue_source: IssueSource,
annotations: ImportAnnotations, annotations: ImportAnnotations,
export_name: Option<ModulePart>, export_name: Option<ModulePart>,
import_usage: ImportUsage,
import_externals: bool, import_externals: bool,
) -> Self { ) -> Self {
EsmAssetReference { EsmAssetReference {
...@@ -373,6 +377,7 @@ impl EsmAssetReference { ...@@ -373,6 +377,7 @@ impl EsmAssetReference {
issue_source, issue_source,
annotations, annotations,
export_name, export_name,
import_usage,
import_externals, import_externals,
is_pure_import: true, is_pure_import: true,
} }
...@@ -512,12 +517,16 @@ impl ChunkableModuleReference for EsmAssetReference { ...@@ -512,12 +517,16 @@ impl ChunkableModuleReference for EsmAssetReference {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn export_usage(&self) -> Vc<ExportUsage> { fn binding_usage(&self) -> Vc<BindingUsage> {
match &self.export_name { BindingUsage {
Some(ModulePart::Export(export_name)) => ExportUsage::named(export_name.clone()), import: self.import_usage.clone(),
Some(ModulePart::Evaluation) => ExportUsage::evaluation(), export: match &self.export_name {
_ => ExportUsage::all(), Some(ModulePart::Export(export_name)) => ExportUsage::Named(export_name.clone()),
Some(ModulePart::Evaluation) => ExportUsage::Evaluation,
_ => ExportUsage::All,
},
} }
.cell()
} }
} }
...@@ -529,6 +538,13 @@ impl EsmAssetReference { ...@@ -529,6 +538,13 @@ impl EsmAssetReference {
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let this = &*self.await?; let this = &*self.await?;
if *chunking_context
.is_reference_unused(Vc::upcast(self))
.await?
{
return Ok(CodeGeneration::empty());
}
// only chunked references can be imported // only chunked references can be imported
if this.annotations.chunking_type().is_none_or(|v| v != "none") { if this.annotations.chunking_type().is_none_or(|v| v != "none") {
let import_externals = this.import_externals; let import_externals = this.import_externals;
...@@ -571,7 +587,7 @@ impl EsmAssetReference { ...@@ -571,7 +587,7 @@ impl EsmAssetReference {
} }
if merged_index.is_some() if merged_index.is_some()
&& matches!(*self.export_usage().await?, ExportUsage::Evaluation) && matches!(this.export_name, Some(ModulePart::Evaluation))
{ {
// No need to import, the module was already executed and is available in // No need to import, the module was already executed and is available in
// the same scope hoisting group (unless it's a // the same scope hoisting group (unless it's a
......
...@@ -21,7 +21,7 @@ use turbopack_core::{ ...@@ -21,7 +21,7 @@ use turbopack_core::{
ident::AssetIdent, ident::AssetIdent,
issue::{IssueExt, IssueSeverity, StyledString, analyze::AnalyzeIssue}, issue::{IssueExt, IssueSeverity, StyledString, analyze::AnalyzeIssue},
module::Module, module::Module,
module_graph::export_usage::ModuleExportUsageInfo, module_graph::binding_usage_info::ModuleExportUsageInfo,
reference::ModuleReference, reference::ModuleReference,
resolve::ModulePart, resolve::ModulePart,
}; };
......
...@@ -42,7 +42,7 @@ use serde::{Deserialize, Serialize}; ...@@ -42,7 +42,7 @@ use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
atoms::{Atom, Wtf8Atom, atom}, atoms::{Atom, Wtf8Atom, atom},
common::{ common::{
GLOBALS, Globals, Span, Spanned, GLOBALS, Globals, Span, Spanned, SyntaxContext,
comments::{CommentKind, Comments}, comments::{CommentKind, Comments},
errors::{DiagnosticId, HANDLER, Handler}, errors::{DiagnosticId, HANDLER, Handler},
pass::AstNodePath, pass::AstNodePath,
...@@ -79,7 +79,7 @@ use turbopack_core::{ ...@@ -79,7 +79,7 @@ use turbopack_core::{
reference::{ModuleReference, ModuleReferences}, reference::{ModuleReference, ModuleReferences},
reference_type::{CommonJsReferenceSubType, ReferenceType}, reference_type::{CommonJsReferenceSubType, ReferenceType},
resolve::{ resolve::{
FindContextFileResult, ModulePart, find_context_file, FindContextFileResult, ImportUsage, ModulePart, find_context_file,
origin::{PlainResolveOrigin, ResolveOrigin, ResolveOriginExt}, origin::{PlainResolveOrigin, ResolveOrigin, ResolveOriginExt},
parse::Request, parse::Request,
pattern::Pattern, pattern::Pattern,
...@@ -134,7 +134,7 @@ use crate::{ ...@@ -134,7 +134,7 @@ use crate::{
analyzer::{ analyzer::{
ConstantNumber, ConstantString, JsValueUrlKind, RequireContextValue, ConstantNumber, ConstantString, JsValueUrlKind, RequireContextValue,
builtin::early_replace_builtin, builtin::early_replace_builtin,
graph::{ConditionalKind, EffectArg, EvalContext, VarGraph}, graph::{ConditionalKind, DeclUsage, EffectArg, EvalContext, VarGraph},
imports::{ImportAnnotations, ImportAttributes, ImportedSymbol, Reexport}, imports::{ImportAnnotations, ImportAttributes, ImportedSymbol, Reexport},
parse_require_context, parse_require_context,
top_level_await::has_top_level_await, top_level_await::has_top_level_await,
...@@ -745,6 +745,51 @@ async fn analyze_ecmascript_module_internal( ...@@ -745,6 +745,51 @@ async fn analyze_ecmascript_module_internal(
}) })
}; };
let mut import_usage =
FxHashMap::with_capacity_and_hasher(var_graph.import_usages.len(), Default::default());
for (reference, usage) in &var_graph.import_usages {
// TODO make this more efficient, i.e. cache the result?
if let DeclUsage::Bindings(ids) = usage {
// compute transitive closure of `ids` over `top_level_mappings`
let mut visited = ids.clone();
let mut stack = ids.iter().collect::<Vec<_>>();
let mut has_global_usage = false;
while let Some(id) = stack.pop() {
match var_graph.decl_usages.get(id) {
Some(DeclUsage::SideEffects) => {
has_global_usage = true;
break;
}
Some(DeclUsage::Bindings(callers)) => {
for caller in callers {
if visited.insert(caller.clone()) {
stack.push(caller);
}
}
}
_ => {}
}
}
// Collect all `visited` declarations which are exported
import_usage.insert(
*reference,
if has_global_usage {
ImportUsage::SideEffects
} else {
ImportUsage::Exports(
var_graph
.exports
.iter()
.filter(|(_, id)| visited.contains(*id))
.map(|(exported, _)| exported.as_str().into())
.collect(),
)
},
);
}
}
let span = tracing::trace_span!("esm import references"); let span = tracing::trace_span!("esm import references");
let import_references = async { let import_references = async {
let mut import_references = Vec::with_capacity(eval_context.imports.references().len()); let mut import_references = Vec::with_capacity(eval_context.imports.references().len());
...@@ -785,6 +830,7 @@ async fn analyze_ecmascript_module_internal( ...@@ -785,6 +830,7 @@ async fn analyze_ecmascript_module_internal(
) )
.then(ModulePart::exports), .then(ModulePart::exports),
}, },
import_usage.get(&i).cloned().unwrap_or_default(),
import_externals, import_externals,
) )
.resolved_cell(); .resolved_cell();
...@@ -1416,6 +1462,8 @@ async fn analyze_ecmascript_module_internal( ...@@ -1416,6 +1462,8 @@ async fn analyze_ecmascript_module_internal(
options.tree_shaking_mode, options.tree_shaking_mode,
Some(TreeShakingMode::ReexportsOnly) Some(TreeShakingMode::ReexportsOnly)
) { ) {
// TODO move this logic into Effect creation itself and don't create new
// references after the fact here.
let original_reference = r.await?; let original_reference = r.await?;
if original_reference.export_name.is_none() if original_reference.export_name.is_none()
&& export.is_some() && export.is_some()
...@@ -1434,6 +1482,11 @@ async fn analyze_ecmascript_module_internal( ...@@ -1434,6 +1482,11 @@ async fn analyze_ecmascript_module_internal(
original_reference.issue_source, original_reference.issue_source,
original_reference.annotations.clone(), original_reference.annotations.clone(),
Some(ModulePart::export(export.clone())), Some(ModulePart::export(export.clone())),
// TODO this is correct, but an overapproximation.
// We should have individual import_usage data for
// each export. This would be fixed by moving this
// logic earlier (see TODO above)
original_reference.import_usage.clone(),
original_reference.import_externals, original_reference.import_externals,
) )
.resolved_cell() .resolved_cell()
...@@ -2874,6 +2927,7 @@ async fn handle_free_var_reference( ...@@ -2874,6 +2927,7 @@ async fn handle_free_var_reference(
) => export.clone().map(ModulePart::export), ) => export.clone().map(ModulePart::export),
None => None, None => None,
}, },
ImportUsage::SideEffects,
state.import_externals, state.import_externals,
) )
.resolved_cell()) .resolved_cell())
...@@ -3502,10 +3556,10 @@ fn as_parent_path(ast_path: &AstNodePath<AstParentNodeRef<'_>>) -> Vec<AstParent ...@@ -3502,10 +3556,10 @@ fn as_parent_path(ast_path: &AstNodePath<AstParentNodeRef<'_>>) -> Vec<AstParent
ast_path.iter().map(|n| n.kind()).collect() ast_path.iter().map(|n| n.kind()).collect()
} }
fn for_each_ident_in_pat(pat: &Pat, f: &mut impl FnMut(RcStr)) { pub(crate) fn for_each_ident_in_pat(pat: &Pat, f: &mut impl FnMut(&Atom, SyntaxContext)) {
match pat { match pat {
Pat::Ident(BindingIdent { id, .. }) => { Pat::Ident(BindingIdent { id, .. }) => {
f(id.sym.as_str().into()); f(&id.sym, id.ctxt);
} }
Pat::Array(ArrayPat { elems, .. }) => elems.iter().for_each(|e| { Pat::Array(ArrayPat { elems, .. }) => elems.iter().for_each(|e| {
if let Some(e) = e { if let Some(e) = e {
...@@ -3521,7 +3575,7 @@ fn for_each_ident_in_pat(pat: &Pat, f: &mut impl FnMut(RcStr)) { ...@@ -3521,7 +3575,7 @@ fn for_each_ident_in_pat(pat: &Pat, f: &mut impl FnMut(RcStr)) {
for_each_ident_in_pat(value, f); for_each_ident_in_pat(value, f);
} }
ObjectPatProp::Assign(AssignPatProp { key, .. }) => { ObjectPatProp::Assign(AssignPatProp { key, .. }) => {
f(key.sym.as_str().into()); f(&key.sym, key.ctxt);
} }
ObjectPatProp::Rest(RestPat { arg, .. }) => { ObjectPatProp::Rest(RestPat { arg, .. }) => {
for_each_ident_in_pat(arg, f); for_each_ident_in_pat(arg, f);
...@@ -3654,8 +3708,8 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> { ...@@ -3654,8 +3708,8 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
}; };
let decls = &*var_decl.decls; let decls = &*var_decl.decls;
decls.iter().for_each(|VarDeclarator { name, .. }| { decls.iter().for_each(|VarDeclarator { name, .. }| {
for_each_ident_in_pat(name, &mut |name| { for_each_ident_in_pat(name, &mut |name, _| {
insert_export_binding(name, liveness) insert_export_binding(name.as_str().into(), liveness)
}) })
}); });
} }
......
...@@ -14,7 +14,7 @@ use turbopack_core::{ ...@@ -14,7 +14,7 @@ use turbopack_core::{
}, },
module::Module, module::Module,
reference::ModuleReference, reference::ModuleReference,
resolve::{ExportUsage, ModulePart, ModuleResolveResult}, resolve::{BindingUsage, ExportUsage, ImportUsage, ModulePart, ModuleResolveResult},
}; };
use super::{ use super::{
...@@ -144,8 +144,12 @@ impl ChunkableModuleReference for EcmascriptModulePartReference { ...@@ -144,8 +144,12 @@ impl ChunkableModuleReference for EcmascriptModulePartReference {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn export_usage(&self) -> Vc<ExportUsage> { async fn binding_usage(&self) -> Result<Vc<BindingUsage>> {
*self.export_usage Ok(BindingUsage {
import: ImportUsage::SideEffects,
export: self.export_usage.owned().await?,
}
.cell())
} }
} }
......
...@@ -18,10 +18,11 @@ use turbopack_core::{ ...@@ -18,10 +18,11 @@ use turbopack_core::{
module::Module, module::Module,
module_graph::{ module_graph::{
ModuleGraph, ModuleGraph,
binding_usage_info::{BindingUsageInfo, ModuleExportUsage},
chunk_group_info::ChunkGroup, chunk_group_info::ChunkGroup,
export_usage::{ExportUsageInfo, ModuleExportUsage},
}, },
output::{OutputAsset, OutputAssets}, output::{OutputAsset, OutputAssets},
reference::ModuleReference,
}; };
use turbopack_ecmascript::{ use turbopack_ecmascript::{
async_chunk::module::AsyncLoaderModule, async_chunk::module::AsyncLoaderModule,
...@@ -117,11 +118,19 @@ impl NodeJsChunkingContextBuilder { ...@@ -117,11 +118,19 @@ impl NodeJsChunkingContextBuilder {
self self
} }
pub fn export_usage(mut self, export_usage: Option<ResolvedVc<ExportUsageInfo>>) -> Self { pub fn export_usage(mut self, export_usage: Option<ResolvedVc<BindingUsageInfo>>) -> Self {
self.chunking_context.export_usage = export_usage; self.chunking_context.export_usage = export_usage;
self self
} }
pub fn unused_references(
mut self,
unused_references: Option<ResolvedVc<BindingUsageInfo>>,
) -> Self {
self.chunking_context.unused_references = unused_references;
self
}
pub fn chunking_config<T>(mut self, ty: ResolvedVc<T>, chunking_config: ChunkingConfig) -> Self pub fn chunking_config<T>(mut self, ty: ResolvedVc<T>, chunking_config: ChunkingConfig) -> Self
where where
T: Upcast<Box<dyn ChunkType>>, T: Upcast<Box<dyn ChunkType>>,
...@@ -188,7 +197,9 @@ pub struct NodeJsChunkingContext { ...@@ -188,7 +197,9 @@ pub struct NodeJsChunkingContext {
/// The strategy to use for generating module ids /// The strategy to use for generating module ids
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>, module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
/// The module export usage info, if available. /// The module export usage info, if available.
export_usage: Option<ResolvedVc<ExportUsageInfo>>, export_usage: Option<ResolvedVc<BindingUsageInfo>>,
/// Which references are unused and should be skipped (e.g. during codegen).
unused_references: Option<ResolvedVc<BindingUsageInfo>>,
/// The strategy to use for generating source map source uris /// The strategy to use for generating source map source uris
source_map_source_type: SourceMapSourceType, source_map_source_type: SourceMapSourceType,
/// The chunking configs /// The chunking configs
...@@ -233,6 +244,7 @@ impl NodeJsChunkingContext { ...@@ -233,6 +244,7 @@ impl NodeJsChunkingContext {
source_map_source_type: SourceMapSourceType::TurbopackUri, source_map_source_type: SourceMapSourceType::TurbopackUri,
module_id_strategy: ResolvedVc::upcast(DevModuleIdStrategy::new_resolved()), module_id_strategy: ResolvedVc::upcast(DevModuleIdStrategy::new_resolved()),
export_usage: None, export_usage: None,
unused_references: None,
chunking_configs: Default::default(), chunking_configs: Default::default(),
debug_ids: false, debug_ids: false,
}, },
...@@ -613,12 +625,24 @@ impl ChunkingContext for NodeJsChunkingContext { ...@@ -613,12 +625,24 @@ impl ChunkingContext for NodeJsChunkingContext {
if let Some(export_usage) = self.await?.export_usage { if let Some(export_usage) = self.await?.export_usage {
Ok(export_usage.await?.used_exports(module).await?) Ok(export_usage.await?.used_exports(module).await?)
} else { } else {
// In development mode, we don't have export usage info, so we assume all exports are
// used.
Ok(ModuleExportUsage::all()) Ok(ModuleExportUsage::all())
} }
} }
#[turbo_tasks::function]
async fn is_reference_unused(
self: Vc<Self>,
reference: ResolvedVc<Box<dyn ModuleReference>>,
) -> Result<Vc<bool>> {
if let Some(unused_references) = self.await?.unused_references {
Ok(Vc::cell(
unused_references.await?.is_reference_unused(&reference),
))
} else {
Ok(Vc::cell(false))
}
}
#[turbo_tasks::function] #[turbo_tasks::function]
fn debug_ids_enabled(&self) -> Vc<bool> { fn debug_ids_enabled(&self) -> Vc<bool> {
Vc::cell(self.debug_ids) Vc::cell(self.debug_ids)
......
...@@ -39,7 +39,7 @@ use turbopack_core::{ ...@@ -39,7 +39,7 @@ use turbopack_core::{
file_source::FileSource, file_source::FileSource,
ident::Layer, ident::Layer,
issue::CollectibleIssuesExt, issue::CollectibleIssuesExt,
module_graph::{ModuleGraph, export_usage::compute_export_usage_info}, module_graph::{ModuleGraph, binding_usage_info::compute_binding_usage_info},
reference_type::{InnerAssets, ReferenceType}, reference_type::{InnerAssets, ReferenceType},
resolve::{ resolve::{
ExternalTraced, ExternalType, ExternalTraced, ExternalType,
...@@ -239,8 +239,12 @@ async fn run_inner_operation( ...@@ -239,8 +239,12 @@ async fn run_inner_operation(
struct TestOptions { struct TestOptions {
#[serde(default = "default_tree_shaking_mode")] #[serde(default = "default_tree_shaking_mode")]
tree_shaking_mode: Option<TreeShakingMode>, tree_shaking_mode: Option<TreeShakingMode>,
remove_unused_exports: Option<bool>, #[serde(default = "default_true")]
scope_hoisting: Option<bool>, remove_unused_imports: bool,
#[serde(default = "default_true")]
remove_unused_exports: bool,
#[serde(default = "default_true")]
scope_hoisting: bool,
#[serde(default)] #[serde(default)]
minify: bool, minify: bool,
#[serde(default)] #[serde(default)]
...@@ -251,12 +255,17 @@ fn default_tree_shaking_mode() -> Option<TreeShakingMode> { ...@@ -251,12 +255,17 @@ fn default_tree_shaking_mode() -> Option<TreeShakingMode> {
Some(TreeShakingMode::ReexportsOnly) Some(TreeShakingMode::ReexportsOnly)
} }
fn default_true() -> bool {
true
}
impl Default for TestOptions { impl Default for TestOptions {
fn default() -> Self { fn default() -> Self {
Self { Self {
tree_shaking_mode: default_tree_shaking_mode(), tree_shaking_mode: default_tree_shaking_mode(),
remove_unused_exports: None, remove_unused_exports: default_true(),
scope_hoisting: None, remove_unused_imports: default_true(),
scope_hoisting: default_true(),
minify: false, minify: false,
production_chunking: false, production_chunking: false,
} }
...@@ -351,7 +360,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -351,7 +360,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
compile_time_defines!( compile_time_defines!(
process.turbopack = true, process.turbopack = true,
process.env.TURBOPACK = true, process.env.TURBOPACK = true,
process.env.NODE_ENV = "development", process.env.NODE_ENV = "production",
) )
.resolved_cell(), .resolved_cell(),
) )
...@@ -395,8 +404,6 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -395,8 +404,6 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
.resolved_cell(), .resolved_cell(),
); );
let remove_unused_exports = options.remove_unused_exports.unwrap_or(true);
let asset_context: Vc<Box<dyn AssetContext>> = Vc::upcast(ModuleAssetContext::new( let asset_context: Vc<Box<dyn AssetContext>> = Vc::upcast(ModuleAssetContext::new(
Default::default(), Default::default(),
compile_time_info, compile_time_info,
...@@ -469,7 +476,23 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -469,7 +476,23 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
let entries = get_evaluate_entries(jest_entry_asset, asset_context, None); let entries = get_evaluate_entries(jest_entry_asset, asset_context, None);
let module_graph = ModuleGraph::from_modules(entries.graph_entries(), false); let mut module_graph = ModuleGraph::from_modules(entries.graph_entries(), false);
let binding_usage = if options.remove_unused_imports || options.remove_unused_exports {
Some(
compute_binding_usage_info(
module_graph.to_resolved().await?,
options.remove_unused_imports,
)
.resolve_strongly_consistent()
.await?,
)
} else {
None
};
if options.remove_unused_imports {
module_graph = module_graph.without_unused_references(*binding_usage.unwrap());
}
let mut builder = NodeJsChunkingContext::builder( let mut builder = NodeJsChunkingContext::builder(
project_root.clone(), project_root.clone(),
...@@ -481,7 +504,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -481,7 +504,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
env, env,
RuntimeType::Development, RuntimeType::Development,
) )
.module_merging(options.scope_hoisting.unwrap_or(true)) .module_merging(options.scope_hoisting)
.minify_type(if options.minify { .minify_type(if options.minify {
MinifyType::Minify { MinifyType::Minify {
mangle: Some(MangleType::OptimalSize), mangle: Some(MangleType::OptimalSize),
...@@ -489,15 +512,16 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -489,15 +512,16 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
} else { } else {
MinifyType::NoMinify MinifyType::NoMinify
}) })
.export_usage(if remove_unused_exports { .export_usage(
Some( options
compute_export_usage_info(module_graph.to_resolved().await?) .remove_unused_exports
.resolve_strongly_consistent() .then(|| binding_usage.unwrap()),
.await?, )
) .unused_references(
} else { options
None .remove_unused_exports
}); .then(|| binding_usage.unwrap()),
);
if options.production_chunking { if options.production_chunking {
builder = builder builder = builder
.chunking_config( .chunking_config(
......
...@@ -122,7 +122,7 @@ it('should evaluate !process.turbopack', () => { ...@@ -122,7 +122,7 @@ it('should evaluate !process.turbopack', () => {
}) })
it('should evaluate NODE_ENV', () => { it('should evaluate NODE_ENV', () => {
if (process.env.NODE_ENV !== 'development') { if (process.env.NODE_ENV !== 'production') {
require('fail') require('fail')
import('fail') import('fail')
} }
......
module.exports = {}
function f() {
if (!process.turbopack) {
throw new Error('Turbopack is not enabled')
}
if (process.env.NODE_ENV !== 'development') {
throw new Error('NODE_ENV is not development')
}
}
f()
// if (f.toString().includes("process.turbopack")) {
// throw new Error("process.turbopack is not replaced");
// }
import { x } from './library/x.js'
import { y } from './library/y.js'
y()
function helper() {
return x()
}
export function unused() {
return helper()
}
export function used() {
return 1234
}
import { used } from './a.js'
it('should error when importing an invalid export', () => {
expect(used()).toBe(1234)
expect(globalThis.xBundled).toBeUndefined()
expect(globalThis.yBundled).toBeTruthy()
})
import * as lib from './library/index.js'
lib.y()
function helper() {
return lib.x()
}
export function unused() {
return helper()
}
export function used() {
return 1234
}
import { used } from './a.js'
it('should error when importing an invalid export', () => {
expect(used()).toBe(1234)
// TODO we don't actually want x to be bundled, but currently we can't track this easily.
// See the TODOs in turbopack/crates/turbopack-ecmascript/src/references/mod.rs
expect(globalThis.xBundled).toBeTruthy()
expect(globalThis.yBundled).toBeTruthy()
})
import { x } from './library/x.js'
function bar() {
return x()
}
export { bar as used }
import { used } from './a.js'
it('should error when importing an invalid export', () => {
used()
expect(globalThis.xBundled).toBeTruthy()
})
import { x } from './dep?c'
export default function abc() {
return x
}
abc()
import { x } from './dep?d'
export default class def {
method() {
return x
}
}
import { x } from './dep?e'
export default class def {
method() {
return x
}
}
import { x } from './dep?f'
export default class def {
method() {
return x
}
}
new def().method()
import A from './a'
import './b'
import './c'
import D from './d'
import './e'
import './f'
import a from './dep?a'
import b from './dep?b'
import c from './dep?c'
import d from './dep?d'
import e from './dep?e'
import f from './dep?f'
it('should generate valid code', () => {
expect(A()).toBe('x')
expect(new D().method()).toBe('x')
})
it('a should be used', () => {
expect(a).toBe(true)
})
if (process.env.NODE_ENV === 'production') {
it('b should be unused', () => {
expect(b).toBe(false)
})
}
it('c should be used', () => {
expect(c).toBe(true)
})
if (process.env.NODE_ENV === 'production') {
it('d should be used', () => {
expect(d).toBe(true)
})
it('e should be unused', () => {
expect(e).toBe(false)
})
}
it('f should be used', () => {
expect(f).toBe(true)
})
import B from './b.js'
import { A1 } from './dep1'
export default class A extends B {
constructor() {
super()
}
test() {
super.test()
this.b = new B()
this.a1 = new A1()
}
}
import A from './a.js'
import { A1 } from './dep1'
export default class B {
constructor() {}
test() {
this.a = new A()
this.a2 = new A1()
}
}
import { BaseError, BaseError1, BaseError2, BaseError3 } from './dep2'
export class ExtendedError extends BaseError {
constructor(message) {
super(message)
}
}
export class ExtendedError1 extends BaseError1 {
constructor(message) {
super(message)
}
}
export class ExtendedError2 extends BaseError2 {
myMethod() {}
}
export class ExtendedError3 extends BaseError3 {}
export class ExtendedError4 extends Error {
constructor(message = 'ExtendedError') {
super(message)
}
}
import { A, B, Z, W } from './dep2'
export const A1 = class A1 extends A {
render() {
return new E()
}
}
class B1 extends B {
render() {
return new D()
}
}
export class Z1 extends Z {}
export class E {}
class D {
foo() {
class B2 extends B {}
return B2
}
}
export const isZ = new Z1() instanceof Z
export { W }
export const A = class A {}
export class B {}
export class C {}
export class Y {}
export class Z {}
export function mixin1(_class) {
return _class
}
export function mixin2(_class) {
return _class
}
export function mixin3(_class) {
return _class
}
export function mixin4(_class) {
return _class
}
export function mixin5(_class) {
return _class
}
export function getField() {
return 'test'
}
export class BaseError extends Error {}
export class BaseError1 extends Error {}
export class BaseError2 extends Error {}
export class BaseError3 extends Error {}
export class W {}
export class J {}
export class K {}
var SuperClass = class {}
export { SuperClass }
export const exportsInfoForA = __webpack_exports_info__.A.used
export const exportsInfoForB = __webpack_exports_info__.B.used
export const exportsInfoForC = __webpack_exports_info__.C.used
export const exportsInfoForY = __webpack_exports_info__.Y.used
export const exportsInfoForZ = __webpack_exports_info__.Z.used
export const exportsInfoForW = __webpack_exports_info__.W.used
export const exportsInfoForJ = __webpack_exports_info__.J.used
export const exportsInfoForK = __webpack_exports_info__.K.used
export const exportsInfoForMixin1 = __webpack_exports_info__.mixin1.used
export const exportsInfoForMixin2 = __webpack_exports_info__.mixin2.used
export const exportsInfoForMixin3 = __webpack_exports_info__.mixin3.used
export const exportsInfoForMixin4 = __webpack_exports_info__.mixin4.used
export const exportsInfoForMixin5 = __webpack_exports_info__.mixin5.used
export const exportsInfoForgetField = __webpack_exports_info__.getField.used
export const exportsInfoForBaseError = __webpack_exports_info__.BaseError.used
export const exportsInfoForBaseError1 = __webpack_exports_info__.BaseError1.used
export const exportsInfoForBaseError2 = __webpack_exports_info__.BaseError2.used
export const exportsInfoForBaseError3 = __webpack_exports_info__.BaseError3.used
export const exportsInfoForSuperClass = __webpack_exports_info__.SuperClass.used
import { mixin1, mixin2, mixin3, getField, A, B, C, Y, mixin4 } from './dep2'
export const A1 = class A1 extends A {
render() {
return new E()
}
}
export const B1 = class B1 extends /*#__PURE__*/ mixin1(B) {
render() {
return new E()
}
}
export const C1 = class C1 extends mixin2(Y, /*#__PURE__*/ mixin3(C)) {
render() {
return new D()
}
}
export class Y1 extends /*#__PURE__*/ mixin2(Y) {
constructor() {
super()
this.innerClass = class B2 extends mixin1(B) {}
}
render() {
return new D()
}
}
export class Bar extends /*#__PURE__*/ mixin4(A) {
[/*#__PURE__*/ getField()] = 12
}
export class E {}
const D = class D {}
import {
exportsInfoForA,
exportsInfoForB,
exportsInfoForC,
exportsInfoForY,
exportsInfoForZ,
exportsInfoForW,
exportsInfoForJ,
exportsInfoForK,
exportsInfoForMixin1,
exportsInfoForMixin2,
exportsInfoForMixin3,
exportsInfoForMixin4,
exportsInfoForMixin5,
exportsInfoForBaseError,
exportsInfoForBaseError1,
exportsInfoForBaseError2,
exportsInfoForBaseError3,
exportsInfoForSuperClass,
} from './dep2'
it('should load modules correctly', () => {
require('./module1')
require('./module2')
require('./module3')
require('./module4')
require('./module5')
require('./module6')
require('./module7')
require('./module8')
require('./module9')
})
if (process.env.NODE_ENV === 'production') {
it('W and J should not be used', () => {
expect(exportsInfoForJ).toBe(false)
expect(exportsInfoForW).toBe(false)
})
it('Keep extends with constructor', () => {
expect(exportsInfoForBaseError).toBe(true)
expect(exportsInfoForBaseError1).toBe(true)
expect(exportsInfoForBaseError2).toBe(false)
expect(exportsInfoForBaseError3).toBe(false)
})
}
it('A should be used', () => {
expect(exportsInfoForA).toBe(true)
})
it('B should be used', () => {
expect(exportsInfoForB).toBe(true)
})
it('K should be used', () => {
expect(exportsInfoForK).toBe(true)
})
it('Z used, inner graph can not determine const usage', () => {
expect(exportsInfoForZ).toBe(true)
})
it('SuperClass should be used', () => {
expect(exportsInfoForSuperClass).toBe(true)
})
it('Pure super expression should be unused, another used', () => {
if (process.env.NODE_ENV === 'production') {
expect(exportsInfoForMixin4).toBe(false)
expect(exportsInfoForMixin5).toBe(false)
}
expect(exportsInfoForMixin1).toBe(true)
expect(exportsInfoForMixin2).toBe(true)
expect(exportsInfoForMixin3).toBe(true)
expect(exportsInfoForC).toBe(true)
expect(exportsInfoForY).toBe(true)
})
import { ExtendedError4 } from './c.js'
export default new ExtendedError4()
import { J } from './dep2'
class BaseJ extends J {}
class BaseBaseJ extends BaseJ {}
import { K } from './dep2'
class BaseK extends K {}
class BaseBaseK extends BaseK {}
export default new BaseBaseK()
import { mixin5 } from './dep2'
class Bar extends /*#__PURE__*/ mixin5(null) {
static displayName = 'Point'
}
function test() {
return Bar.displayName
}
import { SuperClass } from './dep2'
var UnusedClass = class extends SuperClass {
constructor() {
super()
}
},
unusedVariable = new UnusedClass()
'use strict'
const supportsClassStaticBlock = require('../../../helpers/supportsClassStaticBlock')
module.exports = () => supportsClassStaticBlock()
import {
A,
B,
getC,
getD,
getE,
getF,
Foo,
Pure,
DateFormatter,
ConditionalExpression,
LogicalExpression,
} from './dep2?decl'
import {
A3,
B3,
C3,
D3,
E3,
F3,
Pure3,
ConditionalExpression3,
LogicalExpression3,
} from './dep3?decl'
export class A1 extends A {
render() {
return new A2()
}
}
export class B1 extends B {
render() {
return new B2()
}
}
// prettier-ignore
export class C1 extends /*#__PURE__*/ getC() {
render() {
return new C2();
}
}
// prettier-ignore
export class D1 extends /*@__PURE__*/ getD() {
render() {
return new D2();
}
}
export class E1 extends getE() {
render() {
return new E2()
}
}
export class F1 extends getF() {
render() {
return new F2()
}
}
function foo(instance) {
return new instance()
}
class Bar extends Foo {
static prop = 42
static a = foo(this).prop
static b = foo(Bar).prop
static c = foo(super.Bar).prop
static inStatic1
static inStatic2
static inStatic3
static {
this.inStatic1 = new Bar().prop
this.inStatic2 = new super.Bar().prop
this.inStatic3 = new this().prop
}
}
class BarA extends Foo {
static prop = 42
static a = foo(this).prop
}
class BarB extends Foo {
static prop = 42
static b = foo(Bar).prop
}
class BarC extends Foo {
static prop = 42
static c = foo(super.Bar).prop
}
class BarPA extends Foo {
static prop = 42
static #a = foo(this).prop
}
class BarPB extends Foo {
static prop = 42
static #b = foo(Bar).prop
}
class BarPC extends Foo {
static prop = 42
static #c = foo(super.Bar).prop
}
const ExpressionFoo = class Bar extends Foo {
static prop = 42
static a = foo(this).prop
static b = foo(Bar).prop
static c = foo(super.Bar).prop
static inStatic1
static inStatic2
static inStatic3
static {
this.inStatic1 = new Bar().prop
this.inStatic2 = new super.Bar().prop
this.inStatic3 = new this().prop
}
}
export class Baz extends Foo {
static prop = 42
static a = foo(this).prop
static b = foo(Bar).prop
static c = foo(super.Bar).prop
static inStatic1
static inStatic2
static inStatic3
static {
this.inStatic1 = new Bar().prop
this.inStatic2 = new super.Bar().prop
this.inStatic3 = new this().prop
}
}
export default class DefaultBar extends Foo {
static prop = 42
static a = foo(this).prop
static b = foo(Bar).prop
static c = foo(super.Bar).prop
static inStatic1
static inStatic2
static inStatic3
static {
this.inStatic1 = new Bar().prop
this.inStatic2 = new super.Bar().prop
this.inStatic3 = new this().prop
}
}
export class ExtendsPure extends Pure {
render() {
return new Pure3()
}
}
export class DateBar extends DateFormatter {
constructor() {
super()
}
render() {}
}
export class ConditionalExpression1 extends ConditionalExpression {
render() {
return new ConditionalExpression3()
}
}
export class LogicalExpression1 extends LogicalExpression {
render() {
return new LogicalExpression3()
}
}
export class A2 extends A3 {}
export class B2 extends B3 {}
export class C2 extends C3 {}
export class D2 extends D3 {}
export class E2 extends E3 {}
export class F2 extends F3 {}
import {
A,
B,
DateFormatter,
getC,
getD,
getE,
getF,
Pure,
ConditionalExpression,
LogicalExpression,
} from './dep2?expr'
import { A3, B3, C3, D3, E3, F3, Pure3 } from './dep3?expr'
export const A1 = class extends A {
render() {
return new A2()
}
}
export const B1 = class extends B {
render() {
return new B2()
}
}
// prettier-ignore
export const C1 = class extends /*#__PURE__*/ getC() {
render() {
return new C2();
}
}
// prettier-ignore
export const D1 = class extends /*@__PURE__*/ getD() {
render() {
return new D2();
}
}
export const E1 = class extends getE() {
render() {
return new E2()
}
}
export const F1 = class extends getF() {
render() {
return new F2()
}
}
export const ExtendsPure = class extends Pure {
render() {
return new Pure3()
}
}
export class DateBar extends DateFormatter {
constructor() {
super()
}
render() {}
}
export class ConditionalExpression1 extends ConditionalExpression {
render() {
return new ConditionalExpression3()
}
}
export class LogicalExpression1 extends LogicalExpression {
render() {
return new LogicalExpression3()
}
}
export const A2 = class extends A3 {}
export const B2 = class extends B3 {}
export const C2 = class extends C3 {}
export const D2 = class extends D3 {}
export const E2 = class extends E3 {}
export const F2 = class extends F3 {}
export class A {}
export class B {}
export const getC = () => class C {}
export const getD = () => class D {}
export const getE = () => class E {}
export const getF = () => class F {}
export class Foo {
static Bar = Foo
}
export class Pure {}
export class DateFormatter extends Date {
constructor() {
super()
this.date = this.getDate()
}
}
export class ConditionalExpression extends (true ? A : B) {}
export class LogicalExpression extends (A || B) {}
export const exportsInfoForA = __webpack_exports_info__.A.used
export const exportsInfoForB = __webpack_exports_info__.B.used
export const exportsInfoForC = __webpack_exports_info__.getC.used
export const exportsInfoForD = __webpack_exports_info__.getD.used
export const exportsInfoForE = __webpack_exports_info__.getE.used
export const exportsInfoForF = __webpack_exports_info__.getF.used
export const exportsInfoForFoo = __webpack_exports_info__.Foo.used
export const exportsInfoForPure = __webpack_exports_info__.Pure.used
export const exportsInfoForDateFormatter =
__webpack_exports_info__.DateFormatter.used
export const exportsInfoForConditionalExpression =
__webpack_exports_info__.ConditionalExpression.used
export const exportsInfoForLogicalExpression =
__webpack_exports_info__.LogicalExpression.used
export class A3 {}
export class B3 {}
export class C3 {}
export class D3 {}
export class E3 {}
export class F3 {}
export class Pure3 {}
export class ConditionalExpression3 extends (true ? A3 : B3) {}
export class LogicalExpression3 extends (A3 || B3) {}
import {
exportsInfoForA as declA,
exportsInfoForB as declB,
exportsInfoForC as declC,
exportsInfoForD as declD,
exportsInfoForE as declE,
exportsInfoForF as declF,
exportsInfoForFoo as declFoo,
exportsInfoForPure as declPure,
exportsInfoForDateFormatter as declDateFormatter,
exportsInfoForConditionalExpression as declConditionalExpression,
exportsInfoForLogicalExpression as declLogicalExpression,
} from './dep2?decl'
import {
exportsInfoForA as exprA,
exportsInfoForB as exprB,
exportsInfoForC as exprC,
exportsInfoForD as exprD,
exportsInfoForE as exprE,
exportsInfoForF as exprF,
exportsInfoForPure as exprPure,
exportsInfoForDateFormatter as exprDateFormatter,
exportsInfoForConditionalExpression as exprConditionalExpression,
exportsInfoForLogicalExpression as exprLogicalExpression,
} from './dep2?expr'
it('should load module correctly', () => {
require('./module-decl')
require('./module-expr')
})
it('A should be used', () => {
expect(declA).toBe(true)
expect(exprA).toBe(true)
})
if (process.env.NODE_ENV === 'production') {
it('B should not be used', () => {
expect(declB).toBe(false)
expect(exprB).toBe(false)
})
}
it('C should be used', () => {
expect(declC).toBe(true)
expect(exprC).toBe(true)
})
if (process.env.NODE_ENV === 'production') {
it('D should not be used', () => {
expect(declD).toBe(false)
expect(exprD).toBe(false)
})
}
it('E should be used', () => {
expect(declE).toBe(true)
expect(exprE).toBe(true)
})
it('F should be used', () => {
if (process.env.NODE_ENV === 'production') {
expect(declPure).toBe(false)
expect(exprPure).toBe(false)
expect(declConditionalExpression).toBe(false)
expect(exprConditionalExpression).toBe(false)
expect(declLogicalExpression).toBe(false)
expect(exprLogicalExpression).toBe(false)
}
// Note: it has side-effects and is not affected by usage of the class
expect(declF).toBe(true)
expect(declFoo).toBe(true)
expect(exprF).toBe(true)
expect(declDateFormatter).toBe(true)
expect(exprDateFormatter).toBe(true)
})
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