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

Turbopack: add flag to switch between envs (#74135)

parent 2514e133
...@@ -3,7 +3,9 @@ use std::{ ...@@ -3,7 +3,9 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use clap::{Args, Parser}; use clap::{Args, Parser, ValueEnum};
use serde::{Deserialize, Serialize};
use turbo_tasks::{NonLocalValue, TaskInput};
use turbopack_cli_utils::issue::IssueSeverityCliOption; use turbopack_cli_utils::issue::IssueSeverityCliOption;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
...@@ -23,6 +25,24 @@ impl Arguments { ...@@ -23,6 +25,24 @@ impl Arguments {
} }
} }
#[derive(
Copy,
Clone,
Debug,
ValueEnum,
PartialEq,
Eq,
Serialize,
Deserialize,
Hash,
TaskInput,
NonLocalValue,
)]
pub enum Target {
Browser,
Node,
}
#[derive(Debug, Args, Clone)] #[derive(Debug, Args, Clone)]
pub struct CommonArguments { pub struct CommonArguments {
/// The entrypoints of the project. Resolved relative to the project's /// The entrypoints of the project. Resolved relative to the project's
...@@ -61,6 +81,10 @@ pub struct CommonArguments { ...@@ -61,6 +81,10 @@ pub struct CommonArguments {
/// MB. /// MB.
#[clap(long)] #[clap(long)]
pub memory_limit: Option<usize>, pub memory_limit: Option<usize>,
/// Target
#[clap(long)]
pub target: Option<Target>,
} }
#[derive(Debug, Args)] #[derive(Debug, Args)]
......
...@@ -13,14 +13,16 @@ use turbo_tasks::{ ...@@ -13,14 +13,16 @@ use turbo_tasks::{
}; };
use turbo_tasks_fs::FileSystem; use turbo_tasks_fs::FileSystem;
use turbo_tasks_memory::MemoryBackend; use turbo_tasks_memory::MemoryBackend;
use turbopack_browser::BrowserChunkingContext;
use turbopack_cli_utils::issue::{ConsoleUi, LogOptions}; use turbopack_cli_utils::issue::{ConsoleUi, LogOptions};
use turbopack_core::{ use turbopack_core::{
asset::Asset, asset::Asset,
chunk::{ chunk::{
availability_info::AvailabilityInfo, ChunkableModule, ChunkingContext, ChunkingContextExt, availability_info::AvailabilityInfo, ChunkingContext, EvaluatableAsset, EvaluatableAssets,
EvaluatableAsset, EvaluatableAssets, MinifyType, MinifyType,
}, },
environment::{BrowserEnvironment, Environment, ExecutionEnvironment}, environment::{BrowserEnvironment, Environment, ExecutionEnvironment, NodeJsEnvironment},
ident::AssetIdent,
issue::{handle_issues, IssueReporter, IssueSeverity}, issue::{handle_issues, IssueReporter, IssueSeverity},
module::Module, module::Module,
output::{OutputAsset, OutputAssets}, output::{OutputAsset, OutputAssets},
...@@ -37,7 +39,7 @@ use turbopack_node::execution_context::ExecutionContext; ...@@ -37,7 +39,7 @@ use turbopack_node::execution_context::ExecutionContext;
use turbopack_nodejs::NodeJsChunkingContext; use turbopack_nodejs::NodeJsChunkingContext;
use crate::{ use crate::{
arguments::BuildArguments, arguments::{BuildArguments, Target},
contexts::{get_client_asset_context, get_client_compile_time_info, NodeEnv}, contexts::{get_client_asset_context, get_client_compile_time_info, NodeEnv},
util::{ util::{
normalize_dirs, normalize_entries, output_fs, project_fs, EntryRequest, EntryRequests, normalize_dirs, normalize_entries, output_fs, project_fs, EntryRequest, EntryRequests,
...@@ -60,6 +62,7 @@ pub struct TurbopackBuildBuilder { ...@@ -60,6 +62,7 @@ pub struct TurbopackBuildBuilder {
show_all: bool, show_all: bool,
log_detail: bool, log_detail: bool,
minify_type: MinifyType, minify_type: MinifyType,
target: Target,
} }
impl TurbopackBuildBuilder { impl TurbopackBuildBuilder {
...@@ -78,6 +81,7 @@ impl TurbopackBuildBuilder { ...@@ -78,6 +81,7 @@ impl TurbopackBuildBuilder {
show_all: false, show_all: false,
log_detail: false, log_detail: false,
minify_type: MinifyType::Minify, minify_type: MinifyType::Minify,
target: Target::Node,
} }
} }
...@@ -111,6 +115,11 @@ impl TurbopackBuildBuilder { ...@@ -111,6 +115,11 @@ impl TurbopackBuildBuilder {
self self
} }
pub fn target(mut self, target: Target) -> Self {
self.target = target;
self
}
pub async fn build(self) -> Result<()> { pub async fn build(self) -> Result<()> {
let task = self.turbo_tasks.spawn_once_task::<(), _>(async move { let task = self.turbo_tasks.spawn_once_task::<(), _>(async move {
let build_result_op = build_internal( let build_result_op = build_internal(
...@@ -126,6 +135,7 @@ impl TurbopackBuildBuilder { ...@@ -126,6 +135,7 @@ impl TurbopackBuildBuilder {
.resolved_cell(), .resolved_cell(),
self.browserslist_query, self.browserslist_query,
self.minify_type, self.minify_type,
self.target,
); );
// Await the result to propagate any errors. // Await the result to propagate any errors.
...@@ -169,18 +179,8 @@ async fn build_internal( ...@@ -169,18 +179,8 @@ async fn build_internal(
entry_requests: ResolvedVc<EntryRequests>, entry_requests: ResolvedVc<EntryRequests>,
browserslist_query: RcStr, browserslist_query: RcStr,
minify_type: MinifyType, minify_type: MinifyType,
target: Target,
) -> Result<Vc<()>> { ) -> Result<Vc<()>> {
let env = Environment::new(Value::new(ExecutionEnvironment::Browser(
BrowserEnvironment {
dom: true,
web_worker: false,
service_worker: false,
browserslist_query: browserslist_query.clone(),
}
.resolved_cell(),
)))
.to_resolved()
.await?;
let output_fs = output_fs(project_dir.clone()); let output_fs = output_fs(project_dir.clone());
let project_fs = project_fs(root_dir.clone()); let project_fs = project_fs(root_dir.clone());
let project_relative = project_dir.strip_prefix(&*root_dir).unwrap(); let project_relative = project_dir.strip_prefix(&*root_dir).unwrap();
...@@ -201,23 +201,55 @@ async fn build_internal( ...@@ -201,23 +201,55 @@ async fn build_internal(
.get_relative_path_to(&*root_path.await?) .get_relative_path_to(&*root_path.await?)
.context("Project path is in root path")?; .context("Project path is in root path")?;
let chunking_context = Vc::upcast( let runtime_type = match *node_env.await? {
NodeEnv::Development => RuntimeType::Development,
NodeEnv::Production => RuntimeType::Production,
};
let chunking_context: Vc<Box<dyn ChunkingContext>> = match target {
Target::Browser => Vc::upcast(
BrowserChunkingContext::builder(
project_path,
build_output_root,
ResolvedVc::cell(build_output_root_to_root_path),
build_output_root,
build_output_root,
build_output_root,
Environment::new(Value::new(ExecutionEnvironment::Browser(
BrowserEnvironment {
dom: true,
web_worker: false,
service_worker: false,
browserslist_query: browserslist_query.clone(),
}
.resolved_cell(),
)))
.to_resolved()
.await?,
runtime_type,
)
.minify_type(minify_type)
.build(),
),
Target::Node => Vc::upcast(
NodeJsChunkingContext::builder( NodeJsChunkingContext::builder(
root_path, project_path,
build_output_root, build_output_root,
ResolvedVc::cell(build_output_root_to_root_path), ResolvedVc::cell(build_output_root_to_root_path),
build_output_root, build_output_root,
build_output_root, build_output_root,
build_output_root, build_output_root,
env, Environment::new(Value::new(ExecutionEnvironment::NodeJsLambda(
match *node_env.await? { NodeJsEnvironment::default().resolved_cell(),
NodeEnv::Development => RuntimeType::Development, )))
NodeEnv::Production => RuntimeType::Production, .to_resolved()
}, .await?,
runtime_type,
) )
.minify_type(minify_type) .minify_type(minify_type)
.build(), .build(),
); ),
};
let compile_time_info = get_client_compile_time_info(browserslist_query, node_env); let compile_time_info = get_client_compile_time_info(browserslist_query, node_env);
let execution_context = let execution_context =
...@@ -282,10 +314,32 @@ async fn build_internal( ...@@ -282,10 +314,32 @@ async fn build_internal(
if let Some(ecmascript) = if let Some(ecmascript) =
ResolvedVc::try_sidecast::<Box<dyn EvaluatableAsset>>(entry_module).await? ResolvedVc::try_sidecast::<Box<dyn EvaluatableAsset>>(entry_module).await?
{ {
Vc::cell(vec![ match target {
Vc::try_resolve_downcast_type::<NodeJsChunkingContext>(chunking_context) Target::Browser => {
chunking_context
.evaluated_chunk_group(
AssetIdent::from_path(
build_output_root
.join(
ecmascript
.ident()
.path()
.file_stem()
.await? .await?
.as_deref()
.unwrap() .unwrap()
.into(),
)
.with_extension("entry.js".into()),
),
EvaluatableAssets::one(*ResolvedVc::upcast(ecmascript)),
Value::new(AvailabilityInfo::Root),
)
.await?
.assets
}
Target::Node => ResolvedVc::cell(vec![
chunking_context
.entry_chunk_group( .entry_chunk_group(
build_output_root build_output_root
.join( .join(
...@@ -306,13 +360,9 @@ async fn build_internal( ...@@ -306,13 +360,9 @@ async fn build_internal(
) )
.await? .await?
.asset, .asset,
]) ]),
} else if let Some(chunkable) = }
ResolvedVc::try_sidecast::<Box<dyn ChunkableModule>>(entry_module).await?
{
chunking_context.root_chunk_group_assets(*chunkable)
} else { } else {
// TODO convert into a serve-able asset
bail!( bail!(
"Entry module is not chunkable, so it can't be used to bootstrap the \ "Entry module is not chunkable, so it can't be used to bootstrap the \
application" application"
...@@ -325,7 +375,7 @@ async fn build_internal( ...@@ -325,7 +375,7 @@ async fn build_internal(
let mut chunks: HashSet<ResolvedVc<Box<dyn OutputAsset>>> = HashSet::new(); let mut chunks: HashSet<ResolvedVc<Box<dyn OutputAsset>>> = HashSet::new();
for chunk_group in entry_chunk_groups { for chunk_group in entry_chunk_groups {
chunks.extend(&*all_assets_from_entries(chunk_group).await?); chunks.extend(&*all_assets_from_entries(*chunk_group).await?);
} }
chunks chunks
...@@ -361,6 +411,7 @@ pub async fn build(args: &BuildArguments) -> Result<()> { ...@@ -361,6 +411,7 @@ pub async fn build(args: &BuildArguments) -> Result<()> {
} else { } else {
MinifyType::Minify MinifyType::Minify
}) })
.target(args.common.target.unwrap_or(Target::Node))
.show_all(args.common.show_all); .show_all(args.common.show_all);
for entry in normalize_entries(&args.common.entries) { for entry in normalize_entries(&args.common.entries) {
......
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