Unverified Commit b8531670 authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

Turbopack: Merge babel-loader and react-compiler configuration logic to avoid…

Turbopack: Merge babel-loader and react-compiler configuration logic to avoid running babel twice (#83502)

Port the logic for configuring react-compiler from JS to Rust.

This fixes two issues:
- Babel could run twice if you had both react compiler enabled and a babel config file.
- We can now emit a warning if we detect you manually configured babel. Previously, this wasn't safe because we could erroneously warn if react compiler was enabled.
parent 34f1f5a0
...@@ -1314,9 +1314,7 @@ impl AppEndpoint { ...@@ -1314,9 +1314,7 @@ impl AppEndpoint {
// polyfill-nomodule.js is a pre-compiled asset distributed as part of next, // polyfill-nomodule.js is a pre-compiled asset distributed as part of next,
// load it as a RawModule. // load it as a RawModule.
let next_package = get_next_package(project.project_path().owned().await?) let next_package = get_next_package(project.project_path().owned().await?).await?;
.owned()
.await?;
let polyfill_source = let polyfill_source =
FileSource::new(next_package.join("dist/build/polyfills/polyfill-nomodule.js")?); FileSource::new(next_package.join("dist/build/polyfills/polyfill-nomodule.js")?);
let polyfill_output_path = client_chunking_context let polyfill_output_path = client_chunking_context
......
...@@ -16,7 +16,7 @@ pub async fn get_postcss_package_mapping( ...@@ -16,7 +16,7 @@ pub async fn get_postcss_package_mapping(
.resolved_cell(), .resolved_cell(),
ImportMapping::PrimaryAlternative( ImportMapping::PrimaryAlternative(
rcstr!("postcss"), rcstr!("postcss"),
Some(get_next_package(project_path.clone()).owned().await?), Some(get_next_package(project_path.clone()).await?),
) )
.resolved_cell(), .resolved_cell(),
]) ])
......
...@@ -736,21 +736,42 @@ pub enum MdxRsOptions { ...@@ -736,21 +736,42 @@ pub enum MdxRsOptions {
#[turbo_tasks::value(shared, operation)] #[turbo_tasks::value(shared, operation)]
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub enum ReactCompilerMode { pub enum ReactCompilerCompilationMode {
Infer, Infer,
Annotation, Annotation,
All, All,
} }
/// Subset of react compiler options impl Default for ReactCompilerCompilationMode {
fn default() -> Self {
Self::Infer
}
}
#[turbo_tasks::value(shared, operation)] #[turbo_tasks::value(shared, operation)]
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ReactCompilerPanicThreshold {
None,
CriticalErrors,
AllErrors,
}
impl Default for ReactCompilerPanicThreshold {
fn default() -> Self {
Self::None
}
}
/// Subset of react compiler options
#[turbo_tasks::value(shared, operation)]
#[derive(Clone, Debug, Default)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ReactCompilerOptions { pub struct ReactCompilerOptions {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(default)]
pub compilation_mode: Option<ReactCompilerMode>, pub compilation_mode: ReactCompilerCompilationMode,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(default)]
pub panic_threshold: Option<RcStr>, pub panic_threshold: ReactCompilerPanicThreshold,
} }
#[derive( #[derive(
...@@ -1304,6 +1325,14 @@ impl NextConfig { ...@@ -1304,6 +1325,14 @@ impl NextConfig {
Ok(config.cell()) Ok(config.cell())
} }
#[turbo_tasks::function]
pub async fn config_file_path(
&self,
project_path: FileSystemPath,
) -> Result<Vc<FileSystemPath>> {
Ok(project_path.join(&self.config_file_name)?.cell())
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn bundle_pages_router_dependencies(&self) -> Vc<bool> { pub fn bundle_pages_router_dependencies(&self) -> Vc<bool> {
Vc::cell(self.bundle_pages_router_dependencies.unwrap_or_default()) Vc::cell(self.bundle_pages_router_dependencies.unwrap_or_default())
...@@ -1388,8 +1417,12 @@ impl NextConfig { ...@@ -1388,8 +1417,12 @@ impl NextConfig {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn webpack_rules(&self, project_path: FileSystemPath) -> Result<Vc<WebpackRules>> { pub async fn webpack_rules(
let Some(turbo_rules) = self.turbopack.as_ref().and_then(|t| t.rules.as_ref()) else { self: Vc<Self>,
project_path: FileSystemPath,
) -> Result<Vc<WebpackRules>> {
let this = self.await?;
let Some(turbo_rules) = this.turbopack.as_ref().and_then(|t| t.rules.as_ref()) else {
return Ok(Vc::cell(Vec::new())); return Ok(Vc::cell(Vec::new()));
}; };
if turbo_rules.is_empty() { if turbo_rules.is_empty() {
...@@ -1412,7 +1445,6 @@ impl NextConfig { ...@@ -1412,7 +1445,6 @@ impl NextConfig {
.collect(), .collect(),
) )
} }
let config_file_path = || project_path.join(&self.config_file_name);
for item in &rule_collection.0 { for item in &rule_collection.0 {
match item { match item {
RuleConfigCollectionItem::Shorthand(loaders) => { RuleConfigCollectionItem::Shorthand(loaders) => {
...@@ -1439,7 +1471,10 @@ impl NextConfig { ...@@ -1439,7 +1471,10 @@ impl NextConfig {
{ {
InvalidLoaderRuleRenameAsIssue { InvalidLoaderRuleRenameAsIssue {
glob: glob.clone(), glob: glob.clone(),
config_file_path: config_file_path()?, config_file_path: self
.config_file_path(project_path.clone())
.owned()
.await?,
rename_as: rename_as.clone(), rename_as: rename_as.clone(),
} }
.resolved_cell() .resolved_cell()
...@@ -1454,7 +1489,10 @@ impl NextConfig { ...@@ -1454,7 +1489,10 @@ impl NextConfig {
} else { } else {
InvalidLoaderRuleConditionIssue { InvalidLoaderRuleConditionIssue {
condition: condition.clone(), condition: condition.clone(),
config_file_path: config_file_path()?, config_file_path: self
.config_file_path(project_path.clone())
.owned()
.await?,
} }
.resolved_cell() .resolved_cell()
.emit(); .emit();
...@@ -1605,18 +1643,12 @@ impl NextConfig { ...@@ -1605,18 +1643,12 @@ impl NextConfig {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn react_compiler(&self) -> Vc<OptionalReactCompilerOptions> { pub fn react_compiler_options(&self) -> Vc<OptionalReactCompilerOptions> {
let options = &self.experimental.react_compiler; let options = &self.experimental.react_compiler;
let options = match options { let options = match options {
Some(ReactCompilerOptionsOrBoolean::Boolean(true)) => { Some(ReactCompilerOptionsOrBoolean::Boolean(true)) => {
OptionalReactCompilerOptions(Some( OptionalReactCompilerOptions(Some(ReactCompilerOptions::default().resolved_cell()))
ReactCompilerOptions {
compilation_mode: None,
panic_threshold: None,
}
.resolved_cell(),
))
} }
Some(ReactCompilerOptionsOrBoolean::Option(options)) => OptionalReactCompilerOptions( Some(ReactCompilerOptionsOrBoolean::Option(options)) => OptionalReactCompilerOptions(
Some(ReactCompilerOptions { ..options.clone() }.resolved_cell()), Some(ReactCompilerOptions { ..options.clone() }.resolved_cell()),
......
...@@ -25,7 +25,7 @@ use crate::{ ...@@ -25,7 +25,7 @@ use crate::{
embed_js::{VIRTUAL_PACKAGE_NAME, next_js_fs}, embed_js::{VIRTUAL_PACKAGE_NAME, next_js_fs},
mode::NextMode, mode::NextMode,
next_client::context::ClientContextType, next_client::context::ClientContextType,
next_config::NextConfig, next_config::{NextConfig, OptionFileSystemPath},
next_edge::unsupported::NextEdgeUnsupportedModuleReplacer, next_edge::unsupported::NextEdgeUnsupportedModuleReplacer,
next_font::google::{ next_font::google::{
GOOGLE_FONTS_INTERNAL_PREFIX, NextFontGoogleCssModuleReplacer, GOOGLE_FONTS_INTERNAL_PREFIX, NextFontGoogleCssModuleReplacer,
...@@ -704,7 +704,7 @@ async fn insert_next_server_special_aliases( ...@@ -704,7 +704,7 @@ async fn insert_next_server_special_aliases(
ServerContextType::AppSSR { app_dir } ServerContextType::AppSSR { app_dir }
| ServerContextType::AppRSC { app_dir, .. } | ServerContextType::AppRSC { app_dir, .. }
| ServerContextType::AppRoute { app_dir, .. } => { | ServerContextType::AppRoute { app_dir, .. } => {
let next_package = get_next_package(app_dir.clone()).owned().await?; let next_package = get_next_package(app_dir.clone()).await?;
import_map.insert_exact_alias( import_map.insert_exact_alias(
rcstr!("styled-jsx"), rcstr!("styled-jsx"),
request_to_import_mapping(next_package.clone(), rcstr!("styled-jsx")), request_to_import_mapping(next_package.clone(), rcstr!("styled-jsx")),
...@@ -1134,7 +1134,7 @@ async fn insert_next_shared_aliases( ...@@ -1134,7 +1134,7 @@ async fn insert_next_shared_aliases(
.resolved_cell(), .resolved_cell(),
); );
let next_package = get_next_package(project_path.clone()).owned().await?; let next_package = get_next_package(project_path.clone()).await?;
import_map.insert_singleton_alias(rcstr!("@swc/helpers"), next_package.clone()); import_map.insert_singleton_alias(rcstr!("@swc/helpers"), next_package.clone());
import_map.insert_singleton_alias(rcstr!("styled-jsx"), next_package.clone()); import_map.insert_singleton_alias(rcstr!("styled-jsx"), next_package.clone());
import_map.insert_singleton_alias(rcstr!("next"), project_path.clone()); import_map.insert_singleton_alias(rcstr!("next"), project_path.clone());
...@@ -1233,8 +1233,17 @@ async fn insert_next_shared_aliases( ...@@ -1233,8 +1233,17 @@ async fn insert_next_shared_aliases(
Ok(()) Ok(())
} }
pub async fn get_next_package(context_directory: FileSystemPath) -> Result<FileSystemPath> {
try_get_next_package(context_directory)
.owned()
.await?
.context("Next.js package not found")
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn get_next_package(context_directory: FileSystemPath) -> Result<Vc<FileSystemPath>> { pub async fn try_get_next_package(
context_directory: FileSystemPath,
) -> Result<Vc<OptionFileSystemPath>> {
let root = context_directory.root().owned().await?; let root = context_directory.root().owned().await?;
let result = resolve( let result = resolve(
context_directory, context_directory,
...@@ -1242,11 +1251,11 @@ pub async fn get_next_package(context_directory: FileSystemPath) -> Result<Vc<Fi ...@@ -1242,11 +1251,11 @@ pub async fn get_next_package(context_directory: FileSystemPath) -> Result<Vc<Fi
Request::parse(Pattern::Constant(rcstr!("next/package.json"))), Request::parse(Pattern::Constant(rcstr!("next/package.json"))),
node_cjs_resolve_options(root), node_cjs_resolve_options(root),
); );
let source = result if let Some(source) = &*result.first_source().await? {
.first_source() Ok(Vc::cell(Some(source.ident().path().await?.parent())))
.await? } else {
.context("Next.js package not found")?; Ok(Vc::cell(None))
Ok(source.ident().path().await?.parent().cell()) }
} }
pub async fn insert_alias_option<const N: usize>( pub async fn insert_alias_option<const N: usize>(
......
...@@ -9,16 +9,13 @@ use turbopack::module_options::{ ...@@ -9,16 +9,13 @@ use turbopack::module_options::{
WebpackLoaderBuiltinConditionSet, WebpackLoaderBuiltinConditionSetMatch, WebpackLoadersOptions, WebpackLoaderBuiltinConditionSet, WebpackLoaderBuiltinConditionSetMatch, WebpackLoadersOptions,
}; };
use turbopack_core::{ use turbopack_core::{
issue::{Issue, IssueExt, IssueSeverity, IssueStage, OptionStyledString, StyledString}, issue::{Issue, IssueSeverity, IssueStage, OptionStyledString, StyledString},
resolve::{ExternalTraced, ExternalType, options::ImportMapping}, resolve::{ExternalTraced, ExternalType, options::ImportMapping},
}; };
use crate::{ use crate::{
next_config::NextConfig, next_config::NextConfig,
next_shared::webpack_rules::{ next_shared::webpack_rules::{babel::get_babel_loader_rules, sass::get_sass_loader_rules},
babel::{detect_likely_babel_loader, get_babel_loader_rules},
sass::{detect_likely_sass_loader, get_sass_loader_rules},
},
}; };
pub(crate) mod babel; pub(crate) mod babel;
...@@ -147,63 +144,14 @@ pub async fn webpack_loader_options( ...@@ -147,63 +144,14 @@ pub async fn webpack_loader_options(
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
builtin_conditions: BTreeSet<WebpackLoaderBuiltinCondition>, builtin_conditions: BTreeSet<WebpackLoaderBuiltinCondition>,
) -> Result<Vc<OptionWebpackLoadersOptions>> { ) -> Result<Vc<OptionWebpackLoadersOptions>> {
let mut rules = next_config let user_rules = next_config.webpack_rules(project_path.clone()).await?;
.webpack_rules(project_path.clone()) let mut rules = (*user_rules).clone();
.owned()
.await?;
let config_file_path = async || project_path.join(&next_config.await?.config_file_name); rules.append(&mut get_sass_loader_rules(&project_path, next_config, &user_rules).await?);
rules.append(
let use_builtin_sass = next_config &mut get_babel_loader_rules(&project_path, next_config, &builtin_conditions, &user_rules)
.experimental_turbopack_use_builtin_sass() .await?,
.await?; );
if use_builtin_sass.unwrap_or(true) {
if use_builtin_sass.is_none()
&& let Some(glob) = detect_likely_sass_loader(&rules).await?
{
ManuallyConfiguredBuiltinLoaderIssue {
glob,
loader: rcstr!("sass-loader"),
config_key: rcstr!("experimental.turbopackUseBuiltinSass"),
config_file_path: config_file_path().await?,
}
.resolved_cell()
.emit()
}
rules.append(&mut get_sass_loader_rules(next_config.sass_config()).await?);
}
// TODO: Enable this warning after babel configuration is fixed
// (https://github.com/vercel/next.js/pull/82676) and the react-compiler logic is moved into
// here. React-compiler is currently configured in JS before it gets to us, which could trigger
// false-positives.
let use_builtin_babel = next_config
.experimental_turbopack_use_builtin_babel()
.await?;
if !builtin_conditions.contains(&WebpackLoaderBuiltinCondition::Foreign)
&& use_builtin_babel.unwrap_or(true)
{
if use_builtin_babel.is_none()
&& let Some(glob) = detect_likely_babel_loader(&rules).await?
{
let _ = glob;
// TODO: Enable this warning after babel configuration is fixed
// (https://github.com/vercel/next.js/pull/82676) and the react-compiler logic is moved into
// here. React-compiler is currently configured in JS before it gets to us, which could
// trigger false-positives.
/*
ManuallyConfiguredBuiltinLoaderIssue {
glob,
loader: rcstr!("babel-loader"),
disable_builtin_config_key: rcstr!("experimental.turbopackUseBuiltinBabel"),
config_file_path: config_file_path().await?,
}
.resolved_cell()
.emit()
*/
}
rules.append(&mut get_babel_loader_rules(project_path.clone()).await?);
}
if rules.is_empty() { if rules.is_empty() {
return Ok(Vc::cell(None)); return Ok(Vc::cell(None));
...@@ -235,7 +183,7 @@ fn loader_runner_package_mapping() -> Result<Vc<ImportMapping>> { ...@@ -235,7 +183,7 @@ fn loader_runner_package_mapping() -> Result<Vc<ImportMapping>> {
} }
#[turbo_tasks::value] #[turbo_tasks::value]
struct ManuallyConfiguredBuiltinLoaderIssue { pub struct ManuallyConfiguredBuiltinLoaderIssue {
glob: RcStr, glob: RcStr,
loader: RcStr, loader: RcStr,
config_key: RcStr, config_key: RcStr,
......
...@@ -2,12 +2,17 @@ use std::{mem::take, sync::LazyLock}; ...@@ -2,12 +2,17 @@ use std::{mem::take, sync::LazyLock};
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use regex::Regex; use regex::Regex;
use serde_json::Value as JsonValue;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack::module_options::LoaderRuleItem; use turbopack::module_options::LoaderRuleItem;
use turbopack_core::issue::IssueExt;
use turbopack_node::transforms::webpack::WebpackLoaderItem; use turbopack_node::transforms::webpack::WebpackLoaderItem;
use crate::{
next_config::NextConfig, next_shared::webpack_rules::ManuallyConfiguredBuiltinLoaderIssue,
};
// Try to match any reasonably-written glob pattern that might be intended to match `*.sass` or // Try to match any reasonably-written glob pattern that might be intended to match `*.sass` or
// `*.scss` (e.g. isn't just a full wildcard match with no extension) // `*.scss` (e.g. isn't just a full wildcard match with no extension)
static SASS_GLOB_RE: LazyLock<Regex> = LazyLock::new(|| { static SASS_GLOB_RE: LazyLock<Regex> = LazyLock::new(|| {
...@@ -17,7 +22,9 @@ static SASS_GLOB_RE: LazyLock<Regex> = LazyLock::new(|| { ...@@ -17,7 +22,9 @@ static SASS_GLOB_RE: LazyLock<Regex> = LazyLock::new(|| {
static SASS_LOADER_RE: LazyLock<Regex> = static SASS_LOADER_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(^|/)@?sass[-/]loader($|/|\.)").unwrap()); LazyLock::new(|| Regex::new(r"(^|/)@?sass[-/]loader($|/|\.)").unwrap());
pub async fn detect_likely_sass_loader( /// Detect manually-configured sass loaders. This is used to generate a warning, suggesting using
/// the built-in sass support.
async fn detect_likely_sass_loader(
webpack_rules: &[(RcStr, LoaderRuleItem)], webpack_rules: &[(RcStr, LoaderRuleItem)],
) -> Result<Option<RcStr>> { ) -> Result<Option<RcStr>> {
for (glob, rule) in webpack_rules { for (glob, rule) in webpack_rules {
...@@ -35,9 +42,35 @@ pub async fn detect_likely_sass_loader( ...@@ -35,9 +42,35 @@ pub async fn detect_likely_sass_loader(
} }
pub async fn get_sass_loader_rules( pub async fn get_sass_loader_rules(
sass_options: Vc<JsonValue>, project_path: &FileSystemPath,
next_config: Vc<NextConfig>,
user_webpack_rules: &[(RcStr, LoaderRuleItem)],
) -> Result<Vec<(RcStr, LoaderRuleItem)>> { ) -> Result<Vec<(RcStr, LoaderRuleItem)>> {
let sass_options = sass_options.await?; let use_builtin_sass = next_config
.experimental_turbopack_use_builtin_sass()
.await?;
match *use_builtin_sass {
Some(true) => {}
Some(false) => return Ok(Vec::new()),
None => {
if let Some(glob) = detect_likely_sass_loader(user_webpack_rules).await? {
ManuallyConfiguredBuiltinLoaderIssue {
glob,
loader: rcstr!("sass-loader"),
config_key: rcstr!("experimental.turbopackUseBuiltinSass"),
config_file_path: next_config
.config_file_path(project_path.clone())
.owned()
.await?,
}
.resolved_cell()
.emit();
}
}
}
let sass_options = next_config.sass_config().await?;
let Some(mut sass_options) = sass_options.as_object().cloned() else { let Some(mut sass_options) = sass_options.as_object().cloned() else {
bail!("sass_options must be an object"); bail!("sass_options must be an object");
}; };
......
...@@ -249,7 +249,7 @@ pub async fn load_next_js_template( ...@@ -249,7 +249,7 @@ pub async fn load_next_js_template(
let content = file_content_rope(template_path.read()).await?; let content = file_content_rope(template_path.read()).await?;
let content = content.to_str()?; let content = content.to_str()?;
let package_root = &*get_next_package(project_path).await?; let package_root = get_next_package(project_path).await?;
let content = expand_next_js_template( let content = expand_next_js_template(
&content, &content,
......
...@@ -100,6 +100,7 @@ async function getCacheCharacteristics( ...@@ -100,6 +100,7 @@ async function getCacheCharacteristics(
reactCompilerPlugins ??= [] reactCompilerPlugins ??= []
const hasReactCompiler = const hasReactCompiler =
reactCompilerPlugins.length !== 0 && reactCompilerPlugins.length !== 0 &&
!loaderOptions.isServer &&
!/[/\\]node_modules[/\\]/.test(filename) && !/[/\\]node_modules[/\\]/.test(filename) &&
!reactCompilerExclude?.(filename) && !reactCompilerExclude?.(filename) &&
(await isReactCompilerRequired(filename)) (await isReactCompilerRequired(filename))
...@@ -484,7 +485,7 @@ function getCacheKey(cacheCharacteristics: CharacteristicsGermaneToCaching) { ...@@ -484,7 +485,7 @@ function getCacheKey(cacheCharacteristics: CharacteristicsGermaneToCaching) {
(hasModuleExports ? 0b010000 : 0) | (hasModuleExports ? 0b010000 : 0) |
(hasReactCompiler ? 0b100000 : 0) (hasReactCompiler ? 0b100000 : 0)
// separate strings will null bytes, assuming null bytes are not valid in file // separate strings with null bytes, assuming null bytes are not valid in file
// paths // paths
return `${configFilePath || ''}\x00${fileExt}\x00${flags}` return `${configFilePath || ''}\x00${fileExt}\x00${flags}`
} }
......
...@@ -68,6 +68,7 @@ export type NextBabelLoaderOptionDefaultPresets = NextBabelLoaderBaseOptions & { ...@@ -68,6 +68,7 @@ export type NextBabelLoaderOptionDefaultPresets = NextBabelLoaderBaseOptions & {
*/ */
export type NextBabelLoaderOptionStandalone = NextBabelLoaderBaseOptions & { export type NextBabelLoaderOptionStandalone = NextBabelLoaderBaseOptions & {
transformMode: 'standalone' transformMode: 'standalone'
isServer: boolean
} }
export type NextBabelLoaderOptions = export type NextBabelLoaderOptions =
......
import path from 'path' import path from 'path'
import type { import type { ReactCompilerOptions } from '../server/config-shared'
ReactCompilerOptions,
TurbopackLoaderOptions,
} from '../server/config-shared'
import type { NextBabelLoaderOptions } from './babel/loader/types' import type { NextBabelLoaderOptions } from './babel/loader/types'
function getReactCompiler() { function getReactCompiler() {
...@@ -103,10 +100,11 @@ const getReactCompilerLoader = ( ...@@ -103,10 +100,11 @@ const getReactCompilerLoader = (
return undefined return undefined
} }
const babelLoaderOptions: NextBabelLoaderOptions & TurbopackLoaderOptions = { const babelLoaderOptions: NextBabelLoaderOptions = {
transformMode: 'standalone', transformMode: 'standalone',
cwd, cwd,
reactCompilerPlugins, reactCompilerPlugins,
isServer,
} }
if (reactCompilerExclude) { if (reactCompilerExclude) {
babelLoaderOptions.reactCompilerExclude = reactCompilerExclude babelLoaderOptions.reactCompilerExclude = reactCompilerExclude
......
...@@ -10,7 +10,6 @@ import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile' ...@@ -10,7 +10,6 @@ import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile'
import { downloadNativeNextSwc, downloadWasmSwc } from '../../lib/download-swc' import { downloadNativeNextSwc, downloadWasmSwc } from '../../lib/download-swc'
import type { import type {
NextConfigComplete, NextConfigComplete,
ReactCompilerOptions,
TurbopackLoaderBuiltinCondition, TurbopackLoaderBuiltinCondition,
TurbopackLoaderItem, TurbopackLoaderItem,
TurbopackRuleCondition, TurbopackRuleCondition,
...@@ -19,7 +18,6 @@ import type { ...@@ -19,7 +18,6 @@ import type {
} from '../../server/config-shared' } from '../../server/config-shared'
import { isDeepStrictEqual } from 'util' import { isDeepStrictEqual } from 'util'
import { type DefineEnvOptions, getDefineEnv } from '../define-env' import { type DefineEnvOptions, getDefineEnv } from '../define-env'
import { getReactCompilerLoader } from '../get-babel-loader-config'
import type { import type {
NapiPartialProjectOptions, NapiPartialProjectOptions,
NapiProjectOptions, NapiProjectOptions,
...@@ -795,67 +793,12 @@ function bindingToApi( ...@@ -795,67 +793,12 @@ function bindingToApi(
} }
} }
/**
* Returns a new copy of next.js config object to avoid mutating the original.
*
* Also it does some augmentation to the configuration as well, for example set the
* turbopack's rules if `experimental.reactCompilerOptions` is set.
*/
function augmentNextConfig(
originalNextConfig: NextConfigComplete,
projectPath: string
): Record<string, any> {
let nextConfig = { ...originalNextConfig }
// TODO: Merge this with `crates/next-core/src/next_shared/webpack_rules/babel.rs` so that we're
// not configuring babel in two different places (potentially causing it to run twice)
const reactCompilerOptions = nextConfig.experimental?.reactCompiler
const reactCompilerLoader = getReactCompilerLoader(
nextConfig.experimental?.reactCompiler,
projectPath,
/* isServer */ false,
/* reactCompilerExclude */ undefined
)
if (reactCompilerLoader != null) {
const options: ReactCompilerOptions =
typeof reactCompilerOptions === 'object' ? reactCompilerOptions : {}
nextConfig.turbopack = {
...originalNextConfig.turbopack,
rules: {
...originalNextConfig.turbopack.rules,
// assumption: there is no collision with this glob key
'{*.{js,jsx,ts,tsx,cjs,mjs,mts,cts},react-compiler-builtin-rule}': {
loaders: [reactCompilerLoader],
condition: {
all: [
'browser',
{ not: 'foreign' },
{
content:
options.compilationMode === 'annotation'
? /['"]use memo['"]/
: !options.compilationMode ||
options.compilationMode === 'infer'
? // Matches declaration or useXXX or </ (closing jsx) or /> (self closing jsx)
/['"]use memo['"]|\Wuse[A-Z]|<\/|\/>/
: undefined,
},
],
},
},
},
}
}
return nextConfig
}
async function serializeNextConfig( async function serializeNextConfig(
nextConfig: NextConfigComplete, nextConfig: NextConfigComplete,
projectPath: string projectPath: string
): Promise<string> { ): Promise<string> {
// Avoid mutating the existing `nextConfig` object. NOTE: This does a shallow clone. // Avoid mutating the existing `nextConfig` object. NOTE: This is only a shallow clone.
let nextConfigSerializable = augmentNextConfig(nextConfig, projectPath) let nextConfigSerializable: Record<string, any> = { ...nextConfig }
nextConfigSerializable.generateBuildId = nextConfigSerializable.generateBuildId =
await nextConfigSerializable.generateBuildId?.() await nextConfigSerializable.generateBuildId?.()
......
...@@ -517,8 +517,13 @@ export interface ExperimentalConfig { ...@@ -517,8 +517,13 @@ export interface ExperimentalConfig {
turbopackUseSystemTlsCerts?: boolean turbopackUseSystemTlsCerts?: boolean
/** /**
* Set this to `false` to disable the automatic configuration of the babel loader when a babel * Set this to `false` to disable the automatic configuration of the babel loader when a Babel
* configuration file is present. The babel loader configuration is enabled by default. * configuration file is present. This option is enabled by default.
*
* If this is set to `false`, but `experimental.reactCompiler` is `true`, the built-in Babel will
* still be configured, but any Babel configuration files on disk will be ignored. If you wish to
* use React Compiler with a different manually-configured `babel-loader`, you should disable both
* this and `experimental.reactCompiler`.
*/ */
turbopackUseBuiltinBabel?: boolean turbopackUseBuiltinBabel?: boolean
......
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