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 {
// polyfill-nomodule.js is a pre-compiled asset distributed as part of next,
// load it as a RawModule.
let next_package = get_next_package(project.project_path().owned().await?)
.owned()
.await?;
let next_package = get_next_package(project.project_path().owned().await?).await?;
let polyfill_source =
FileSource::new(next_package.join("dist/build/polyfills/polyfill-nomodule.js")?);
let polyfill_output_path = client_chunking_context
......
......@@ -16,7 +16,7 @@ pub async fn get_postcss_package_mapping(
.resolved_cell(),
ImportMapping::PrimaryAlternative(
rcstr!("postcss"),
Some(get_next_package(project_path.clone()).owned().await?),
Some(get_next_package(project_path.clone()).await?),
)
.resolved_cell(),
])
......
......@@ -736,21 +736,42 @@ pub enum MdxRsOptions {
#[turbo_tasks::value(shared, operation)]
#[derive(Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub enum ReactCompilerMode {
pub enum ReactCompilerCompilationMode {
Infer,
Annotation,
All,
}
/// Subset of react compiler options
impl Default for ReactCompilerCompilationMode {
fn default() -> Self {
Self::Infer
}
}
#[turbo_tasks::value(shared, operation)]
#[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")]
pub struct ReactCompilerOptions {
#[serde(skip_serializing_if = "Option::is_none")]
pub compilation_mode: Option<ReactCompilerMode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub panic_threshold: Option<RcStr>,
#[serde(default)]
pub compilation_mode: ReactCompilerCompilationMode,
#[serde(default)]
pub panic_threshold: ReactCompilerPanicThreshold,
}
#[derive(
......@@ -1304,6 +1325,14 @@ impl NextConfig {
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]
pub fn bundle_pages_router_dependencies(&self) -> Vc<bool> {
Vc::cell(self.bundle_pages_router_dependencies.unwrap_or_default())
......@@ -1388,8 +1417,12 @@ impl NextConfig {
}
#[turbo_tasks::function]
pub async fn webpack_rules(&self, project_path: FileSystemPath) -> Result<Vc<WebpackRules>> {
let Some(turbo_rules) = self.turbopack.as_ref().and_then(|t| t.rules.as_ref()) else {
pub async fn webpack_rules(
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()));
};
if turbo_rules.is_empty() {
......@@ -1412,7 +1445,6 @@ impl NextConfig {
.collect(),
)
}
let config_file_path = || project_path.join(&self.config_file_name);
for item in &rule_collection.0 {
match item {
RuleConfigCollectionItem::Shorthand(loaders) => {
......@@ -1439,7 +1471,10 @@ impl NextConfig {
{
InvalidLoaderRuleRenameAsIssue {
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(),
}
.resolved_cell()
......@@ -1454,7 +1489,10 @@ impl NextConfig {
} else {
InvalidLoaderRuleConditionIssue {
condition: condition.clone(),
config_file_path: config_file_path()?,
config_file_path: self
.config_file_path(project_path.clone())
.owned()
.await?,
}
.resolved_cell()
.emit();
......@@ -1605,18 +1643,12 @@ impl NextConfig {
}
#[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 = match options {
Some(ReactCompilerOptionsOrBoolean::Boolean(true)) => {
OptionalReactCompilerOptions(Some(
ReactCompilerOptions {
compilation_mode: None,
panic_threshold: None,
}
.resolved_cell(),
))
OptionalReactCompilerOptions(Some(ReactCompilerOptions::default().resolved_cell()))
}
Some(ReactCompilerOptionsOrBoolean::Option(options)) => OptionalReactCompilerOptions(
Some(ReactCompilerOptions { ..options.clone() }.resolved_cell()),
......
......@@ -25,7 +25,7 @@ use crate::{
embed_js::{VIRTUAL_PACKAGE_NAME, next_js_fs},
mode::NextMode,
next_client::context::ClientContextType,
next_config::NextConfig,
next_config::{NextConfig, OptionFileSystemPath},
next_edge::unsupported::NextEdgeUnsupportedModuleReplacer,
next_font::google::{
GOOGLE_FONTS_INTERNAL_PREFIX, NextFontGoogleCssModuleReplacer,
......@@ -704,7 +704,7 @@ async fn insert_next_server_special_aliases(
ServerContextType::AppSSR { app_dir }
| ServerContextType::AppRSC { 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(
rcstr!("styled-jsx"),
request_to_import_mapping(next_package.clone(), rcstr!("styled-jsx")),
......@@ -1134,7 +1134,7 @@ async fn insert_next_shared_aliases(
.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!("styled-jsx"), next_package.clone());
import_map.insert_singleton_alias(rcstr!("next"), project_path.clone());
......@@ -1233,8 +1233,17 @@ async fn insert_next_shared_aliases(
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]
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 result = resolve(
context_directory,
......@@ -1242,11 +1251,11 @@ pub async fn get_next_package(context_directory: FileSystemPath) -> Result<Vc<Fi
Request::parse(Pattern::Constant(rcstr!("next/package.json"))),
node_cjs_resolve_options(root),
);
let source = result
.first_source()
.await?
.context("Next.js package not found")?;
Ok(source.ident().path().await?.parent().cell())
if let Some(source) = &*result.first_source().await? {
Ok(Vc::cell(Some(source.ident().path().await?.parent())))
} else {
Ok(Vc::cell(None))
}
}
pub async fn insert_alias_option<const N: usize>(
......
......@@ -9,16 +9,13 @@ use turbopack::module_options::{
WebpackLoaderBuiltinConditionSet, WebpackLoaderBuiltinConditionSetMatch, WebpackLoadersOptions,
};
use turbopack_core::{
issue::{Issue, IssueExt, IssueSeverity, IssueStage, OptionStyledString, StyledString},
issue::{Issue, IssueSeverity, IssueStage, OptionStyledString, StyledString},
resolve::{ExternalTraced, ExternalType, options::ImportMapping},
};
use crate::{
next_config::NextConfig,
next_shared::webpack_rules::{
babel::{detect_likely_babel_loader, get_babel_loader_rules},
sass::{detect_likely_sass_loader, get_sass_loader_rules},
},
next_shared::webpack_rules::{babel::get_babel_loader_rules, sass::get_sass_loader_rules},
};
pub(crate) mod babel;
......@@ -147,63 +144,14 @@ pub async fn webpack_loader_options(
next_config: Vc<NextConfig>,
builtin_conditions: BTreeSet<WebpackLoaderBuiltinCondition>,
) -> Result<Vc<OptionWebpackLoadersOptions>> {
let mut rules = next_config
.webpack_rules(project_path.clone())
.owned()
.await?;
let user_rules = next_config.webpack_rules(project_path.clone()).await?;
let mut rules = (*user_rules).clone();
let config_file_path = async || project_path.join(&next_config.await?.config_file_name);
let use_builtin_sass = next_config
.experimental_turbopack_use_builtin_sass()
.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?);
}
rules.append(&mut get_sass_loader_rules(&project_path, next_config, &user_rules).await?);
rules.append(
&mut get_babel_loader_rules(&project_path, next_config, &builtin_conditions, &user_rules)
.await?,
);
if rules.is_empty() {
return Ok(Vc::cell(None));
......@@ -235,7 +183,7 @@ fn loader_runner_package_mapping() -> Result<Vc<ImportMapping>> {
}
#[turbo_tasks::value]
struct ManuallyConfiguredBuiltinLoaderIssue {
pub struct ManuallyConfiguredBuiltinLoaderIssue {
glob: RcStr,
loader: RcStr,
config_key: RcStr,
......
......@@ -2,12 +2,17 @@ use std::{mem::take, sync::LazyLock};
use anyhow::{Result, bail};
use regex::Regex;
use serde_json::Value as JsonValue;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack::module_options::LoaderRuleItem;
use turbopack_core::issue::IssueExt;
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
// `*.scss` (e.g. isn't just a full wildcard match with no extension)
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> =
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)],
) -> Result<Option<RcStr>> {
for (glob, rule) in webpack_rules {
......@@ -35,9 +42,35 @@ pub async fn detect_likely_sass_loader(
}
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)>> {
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 {
bail!("sass_options must be an object");
};
......
......@@ -249,7 +249,7 @@ pub async fn load_next_js_template(
let content = file_content_rope(template_path.read()).await?;
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(
&content,
......
......@@ -100,6 +100,7 @@ async function getCacheCharacteristics(
reactCompilerPlugins ??= []
const hasReactCompiler =
reactCompilerPlugins.length !== 0 &&
!loaderOptions.isServer &&
!/[/\\]node_modules[/\\]/.test(filename) &&
!reactCompilerExclude?.(filename) &&
(await isReactCompilerRequired(filename))
......@@ -484,7 +485,7 @@ function getCacheKey(cacheCharacteristics: CharacteristicsGermaneToCaching) {
(hasModuleExports ? 0b010000 : 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
return `${configFilePath || ''}\x00${fileExt}\x00${flags}`
}
......
......@@ -68,6 +68,7 @@ export type NextBabelLoaderOptionDefaultPresets = NextBabelLoaderBaseOptions & {
*/
export type NextBabelLoaderOptionStandalone = NextBabelLoaderBaseOptions & {
transformMode: 'standalone'
isServer: boolean
}
export type NextBabelLoaderOptions =
......
import path from 'path'
import type {
ReactCompilerOptions,
TurbopackLoaderOptions,
} from '../server/config-shared'
import type { ReactCompilerOptions } from '../server/config-shared'
import type { NextBabelLoaderOptions } from './babel/loader/types'
function getReactCompiler() {
......@@ -103,10 +100,11 @@ const getReactCompilerLoader = (
return undefined
}
const babelLoaderOptions: NextBabelLoaderOptions & TurbopackLoaderOptions = {
const babelLoaderOptions: NextBabelLoaderOptions = {
transformMode: 'standalone',
cwd,
reactCompilerPlugins,
isServer,
}
if (reactCompilerExclude) {
babelLoaderOptions.reactCompilerExclude = reactCompilerExclude
......
......@@ -10,7 +10,6 @@ import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile'
import { downloadNativeNextSwc, downloadWasmSwc } from '../../lib/download-swc'
import type {
NextConfigComplete,
ReactCompilerOptions,
TurbopackLoaderBuiltinCondition,
TurbopackLoaderItem,
TurbopackRuleCondition,
......@@ -19,7 +18,6 @@ import type {
} from '../../server/config-shared'
import { isDeepStrictEqual } from 'util'
import { type DefineEnvOptions, getDefineEnv } from '../define-env'
import { getReactCompilerLoader } from '../get-babel-loader-config'
import type {
NapiPartialProjectOptions,
NapiProjectOptions,
......@@ -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(
nextConfig: NextConfigComplete,
projectPath: string
): Promise<string> {
// Avoid mutating the existing `nextConfig` object. NOTE: This does a shallow clone.
let nextConfigSerializable = augmentNextConfig(nextConfig, projectPath)
// Avoid mutating the existing `nextConfig` object. NOTE: This is only a shallow clone.
let nextConfigSerializable: Record<string, any> = { ...nextConfig }
nextConfigSerializable.generateBuildId =
await nextConfigSerializable.generateBuildId?.()
......
......@@ -517,8 +517,13 @@ export interface ExperimentalConfig {
turbopackUseSystemTlsCerts?: boolean
/**
* 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.
* Set this to `false` to disable the automatic configuration of the babel loader when a Babel
* 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
......
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