Unverified Commit adcac5df authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Add turbopackIgnoreIssue config to suppress Turbopack warnings (#89682)

## What?

Adds the `experimental.turbopackIgnoreIssue` configuration option, which allows developers to suppress specific Turbopack warnings and errors based on file path, issue title, and/or description patterns. Filtered issues are hidden from both CLI output and the error overlay.

## Why?

Developers need a way to suppress noisy or expected warnings from Turbopack without disabling all warnings. This is useful for:
- Suppressing warnings from third-party code, generated files, or optional dependencies
- Reducing noise in development server output
- Hiding expected issues from the error overlay

## How?

### Configuration → Filtering Pipeline

1. **Config types** (`packages/next/src/server/config-shared.ts`, `config-schema.ts`):
   Each rule has a required `path` (glob string or RegExp) and optional `title`/`description` (exact string or RegExp). All specified fields must match (AND logic).

2. **RegExp serialization** (`packages/next/src/build/swc/index.ts`):
   Converts RegExp objects to `{ source, flags }` and glob strings to `{ type: 'glob', value }` for transfer to Rust.

3. **Rust deserialization** (`crates/next-core/src/next_config.rs`):
   `TurbopackIgnoreIssueRule`, `TurbopackIgnoreIssuePathPattern`, and `TurbopackIgnoreIssueTextPattern` types deserialize the config. A `turbopack_ignore_issue_rules()` turbo-tasks function converts them to `IgnoreIssue` rules with proper cache invalidation.

4. **Issue filtering** (`turbopack/crates/turbopack-core/src/issue/mod.rs`):
   `IssueFilter` is a turbo-tasks value that holds both severity filters and ignore rules. `IgnoreIssuePattern` supports exact string, glob, and regex matching (using `turbo-esregex` for ES-style regex). Matching issues are excluded before severity filtering.

5. **Integration** (`crates/next-api/src/project.rs`, `route.rs`, `empty.rs`):
   `Endpoint::project()` trait method provides access to the project config. `issue_filter()` builds the `IssueFilter` from project config. All issue collection points use the project's dynamic filter instead of the previous hardcoded `NEXT_ISSUE_FILTER`.

### Documentation

- New docs page: `docs/01-app/03-api-reference/05-config/01-next-config-js/turbopackIgnoreIssue.mdx`
- Updated Turbopack reference page with experimental options table: `docs/01-app/03-api-reference/08-turbopack.mdx`

### Testing

E2E test suite (`test/development/app-dir/turbopack-ignore-issue/`):
- **With config**: verifies matching warnings are suppressed from CLI output, matching errors are suppressed from the error overlay, and unrelated pages still compile normally
- **Without config**: verifies warnings and errors appear when no rules are defined

### Dependencies

- Added `turbo-esregex` for ES-style regex support in Rust

## Example

```js
// next.config.js
module.exports = {
  experimental: {
    turbopackIgnoreIssue: [
      { path: '**/vendor/**' },
      { path: 'app/**', title: 'Module not found' },
      { path: /generated\/.*\.ts/, description: /expected error/i },
    ],
  },
}
```
parent 384cb2da
......@@ -9823,6 +9823,7 @@ dependencies = [
"tokio",
"tracing",
"turbo-bincode",
"turbo-esregex",
"turbo-frozenmap",
"turbo-prehash",
"turbo-rcstr",
......
......@@ -2122,6 +2122,11 @@ impl Endpoint for AppEndpoint {
.await?;
Ok(Vc::cell(vec![module_graphs.full]))
}
#[turbo_tasks::function]
async fn project(self: Vc<Self>) -> Result<Vc<Project>> {
Ok(self.await?.app_project.project())
}
}
#[turbo_tasks::value]
......
use anyhow::{Result, bail};
use turbo_tasks::{Completion, Vc};
use turbo_tasks::{Completion, ResolvedVc, Vc};
use turbopack_core::module_graph::GraphEntries;
use crate::route::{Endpoint, EndpointOutput, ModuleGraphs};
use crate::{
project::Project,
route::{Endpoint, EndpointOutput, ModuleGraphs},
};
#[turbo_tasks::value]
pub struct EmptyEndpoint;
pub struct EmptyEndpoint {
project: ResolvedVc<Project>,
}
#[turbo_tasks::value_impl]
impl EmptyEndpoint {
#[turbo_tasks::function]
pub fn new() -> Vc<Self> {
EmptyEndpoint.cell()
pub fn new(project: ResolvedVc<Project>) -> Vc<Self> {
EmptyEndpoint { project }.cell()
}
}
......@@ -41,4 +46,9 @@ impl Endpoint for EmptyEndpoint {
fn module_graphs(self: Vc<Self>) -> Vc<ModuleGraphs> {
Vc::cell(vec![])
}
#[turbo_tasks::function]
fn project(&self) -> Vc<Project> {
*self.project
}
}
......@@ -253,4 +253,9 @@ impl Endpoint for InstrumentationEndpoint {
let module_graph = this.project.module_graph(module).to_resolved().await?;
Ok(Vc::cell(vec![module_graph]))
}
#[turbo_tasks::function]
fn project(&self) -> Vc<Project> {
*self.project
}
}
......@@ -393,4 +393,9 @@ impl Endpoint for MiddlewareEndpoint {
.await?;
Ok(Vc::cell(vec![module_graph]))
}
#[turbo_tasks::function]
fn project(&self) -> Vc<Project> {
*self.project
}
}
......@@ -1734,6 +1734,11 @@ impl Endpoint for PageEndpoint {
vec![ssr_module_graph]
}))
}
#[turbo_tasks::function]
async fn project(self: Vc<Self>) -> Result<Vc<Project>> {
Ok(self.await?.pages_project.project())
}
}
#[turbo_tasks::value]
......
......@@ -57,8 +57,8 @@ use turbopack_core::{
file_source::FileSource,
ident::Layer,
issue::{
CollectibleIssuesExt, Issue, IssueExt, IssueSeverity, IssueStage, OptionStyledString,
StyledString,
CollectibleIssuesExt, Issue, IssueExt, IssueFilter, IssueSeverity, IssueStage,
OptionStyledString, StyledString,
},
module::Module,
module_graph::{
......@@ -1086,6 +1086,16 @@ impl Project {
*self.next_config
}
/// Build the `IssueFilter` for this project, incorporating any
/// `experimental.turbopackIgnoreIssue` rules from the Next.js config.
#[turbo_tasks::function]
pub async fn issue_filter(self: Vc<Self>) -> Result<Vc<IssueFilter>> {
let ignore_rules = self.next_config().turbopack_ignore_issue_rules().await?;
Ok(IssueFilter::warnings_and_foreign_errors()
.with_ignore_rules(ignore_rules.to_vec())
.cell())
}
#[turbo_tasks::function]
pub(super) fn is_persistent_caching_enabled(&self) -> Vc<bool> {
Vc::cell(self.is_persistent_caching_enabled)
......@@ -1845,7 +1855,7 @@ impl Project {
async fn middleware_endpoint(self: Vc<Self>) -> Result<Vc<Box<dyn Endpoint>>> {
let middleware = self.find_middleware();
let FindContextFileResult::Found(fs_path, _) = &*middleware.await? else {
return Ok(Vc::upcast(EmptyEndpoint::new()));
return Ok(Vc::upcast(EmptyEndpoint::new(self)));
};
let source = Vc::upcast(FileSource::new(fs_path.clone()));
let app_dir = find_app_dir(self.project_path().owned().await?)
......@@ -2029,7 +2039,7 @@ impl Project {
) -> Result<Vc<Box<dyn Endpoint>>> {
let instrumentation = self.find_instrumentation();
let FindContextFileResult::Found(fs_path, _) = &*instrumentation.await? else {
return Ok(Vc::upcast(EmptyEndpoint::new()));
return Ok(Vc::upcast(EmptyEndpoint::new(self)));
};
let source = Vc::upcast(FileSource::new(fs_path.clone()));
let app_dir = find_app_dir(self.project_path().owned().await?)
......
......@@ -64,6 +64,9 @@ pub trait Endpoint {
}
#[turbo_tasks::function]
fn module_graphs(self: Vc<Self>) -> Vc<ModuleGraphs>;
/// The project this endpoint belongs to.
#[turbo_tasks::function]
fn project(self: Vc<Self>) -> Vc<Project>;
}
#[derive(
......
......@@ -12,14 +12,20 @@ use turbo_tasks::{
};
use turbo_tasks_env::EnvMap;
use turbo_tasks_fetch::FetchClientConfig;
use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_fs::{
FileSystemPath,
glob::{Glob, GlobOptions},
};
use turbopack::module_options::{
ConditionContentType, ConditionItem, ConditionPath, ConditionQuery, LoaderRuleItem,
WebpackRules, module_options_context::MdxTransformOptions,
};
use turbopack_core::{
chunk::SourceMapsType,
issue::{Issue, IssueExt, IssueSeverity, IssueStage, OptionStyledString, StyledString},
issue::{
IgnoreIssue, IgnoreIssuePattern, Issue, IssueExt, IssueSeverity, IssueStage,
OptionStyledString, StyledString,
},
resolve::ResolveAliasMap,
};
use turbopack_ecmascript::{OptionTreeShaking, TreeShakingMode};
......@@ -964,6 +970,73 @@ pub enum ReactCompilerOptionsOrBoolean {
#[turbo_tasks::value(transparent)]
pub struct OptionalReactCompilerOptions(Option<ResolvedVc<ReactCompilerOptions>>);
/// Serialized representation of a path pattern for `turbopackIgnoreIssue`.
/// Strings are serialized as `{ "type": "glob", "value": "..." }` and
/// RegExp as `{ "type": "regex", "source": "...", "flags": "..." }`.
#[derive(
Clone, Debug, PartialEq, Deserialize, TraceRawVcs, NonLocalValue, OperationValue, Encode, Decode,
)]
#[serde(tag = "type")]
pub enum TurbopackIgnoreIssuePathPattern {
#[serde(rename = "glob")]
Glob { value: RcStr },
#[serde(rename = "regex")]
Regex { source: RcStr, flags: RcStr },
}
impl TurbopackIgnoreIssuePathPattern {
fn to_ignore_pattern(&self) -> Result<IgnoreIssuePattern> {
match self {
TurbopackIgnoreIssuePathPattern::Glob { value } => Ok(IgnoreIssuePattern::Glob(
Glob::parse(value.clone(), GlobOptions::default())?,
)),
TurbopackIgnoreIssuePathPattern::Regex { source, flags } => {
Ok(IgnoreIssuePattern::Regex(EsRegex::new(source, flags)?))
}
}
}
}
/// Serialized representation of a text pattern (title/description) for
/// `turbopackIgnoreIssue`. Strings are serialized as
/// `{ "type": "string", "value": "..." }` and RegExp as
/// `{ "type": "regex", "source": "...", "flags": "..." }`.
#[derive(
Clone, Debug, PartialEq, Deserialize, TraceRawVcs, NonLocalValue, OperationValue, Encode, Decode,
)]
#[serde(tag = "type")]
pub enum TurbopackIgnoreIssueTextPattern {
#[serde(rename = "string")]
String { value: RcStr },
#[serde(rename = "regex")]
Regex { source: RcStr, flags: RcStr },
}
impl TurbopackIgnoreIssueTextPattern {
fn to_ignore_pattern(&self) -> Result<IgnoreIssuePattern> {
match self {
TurbopackIgnoreIssueTextPattern::String { value } => {
Ok(IgnoreIssuePattern::ExactString(value.clone()))
}
TurbopackIgnoreIssueTextPattern::Regex { source, flags } => {
Ok(IgnoreIssuePattern::Regex(EsRegex::new(source, flags)?))
}
}
}
}
/// A single rule in `experimental.turbopackIgnoreIssue`.
#[derive(
Clone, Debug, PartialEq, Deserialize, TraceRawVcs, NonLocalValue, OperationValue, Encode, Decode,
)]
pub struct TurbopackIgnoreIssueRule {
pub path: TurbopackIgnoreIssuePathPattern,
#[serde(default)]
pub title: Option<TurbopackIgnoreIssueTextPattern>,
#[serde(default)]
pub description: Option<TurbopackIgnoreIssueTextPattern>,
}
#[derive(
Clone,
Debug,
......@@ -1094,6 +1167,9 @@ pub struct ExperimentalConfig {
turbopack_remove_unused_exports: Option<bool>,
/// Enable local analysis to infer side effect free modules. Defaults to true.
turbopack_infer_module_side_effects: Option<bool>,
/// Issue patterns to ignore (suppress) from Turbopack output.
#[serde(default)]
turbopack_ignore_issue: Option<Vec<TurbopackIgnoreIssueRule>>,
/// Devtool option for the segment explorer.
devtool_segment_explorer: Option<bool>,
/// Whether to report inlined system environment variables as warnings or errors.
......@@ -1322,6 +1398,9 @@ pub struct OptionFileSystemPath(Option<FileSystemPath>);
#[turbo_tasks::value(transparent)]
pub struct OptionServerActions(Option<ServerActions>);
#[turbo_tasks::value(transparent)]
pub struct IgnoreIssues(Vec<IgnoreIssue>);
#[turbo_tasks::value(transparent)]
pub struct OptionJsonValue(
#[bincode(with = "turbo_bincode::serde_self_describing")] pub Option<serde_json::Value>,
......@@ -2115,6 +2194,35 @@ impl NextConfig {
),
}
}
/// Returns the list of ignore-issue rules from the experimental config,
/// converted to the `IgnoreIssue` type used by `IssueFilter`.
#[turbo_tasks::function]
pub fn turbopack_ignore_issue_rules(&self) -> Result<Vc<IgnoreIssues>> {
let rules = self
.experimental
.turbopack_ignore_issue
.as_deref()
.unwrap_or_default()
.iter()
.map(|rule| {
Ok(IgnoreIssue {
path: rule.path.to_ignore_pattern()?,
title: rule
.title
.as_ref()
.map(|t| t.to_ignore_pattern())
.transpose()?,
description: rule
.description
.as_ref()
.map(|d| d.to_ignore_pattern())
.transpose()?,
})
})
.collect::<Result<Vec<_>>>()?;
Ok(Vc::cell(rules))
}
}
/// A subset of ts/jsconfig that next.js implicitly
......
......@@ -23,9 +23,10 @@ pub async fn write_analyze_data_with_issues_operation(
app_dir_only: bool,
) -> Result<Vc<WriteAnalyzeResult>> {
let analyze_data_op = write_analyze_data_with_issues_operation_inner(project, app_dir_only);
let filter = project.project().issue_filter();
let (_analyze_data, issues, diagnostics, effects) =
strongly_consistent_catch_collectables(analyze_data_op).await?;
strongly_consistent_catch_collectables(analyze_data_op, filter).await?;
Ok(WriteAnalyzeResult {
issues,
......
......@@ -8,13 +8,16 @@ use next_api::{
operation::OptionEndpoint,
paths::ServerPath,
route::{
EndpointOutputPaths, endpoint_client_changed_operation, endpoint_server_changed_operation,
endpoint_write_to_disk_operation,
Endpoint, EndpointOutputPaths, endpoint_client_changed_operation,
endpoint_server_changed_operation, endpoint_write_to_disk_operation,
},
};
use tracing::Instrument;
use turbo_tasks::{Completion, Effects, OperationVc, ReadRef, Vc};
use turbopack_core::{diagnostics::PlainDiagnostic, issue::PlainIssue};
use turbopack_core::{
diagnostics::PlainDiagnostic,
issue::{IssueFilter, PlainIssue},
};
use crate::next_api::utils::{
DetachedVc, NapiDiagnostic, NapiIssue, RootTask, TurbopackResult,
......@@ -98,6 +101,19 @@ impl Deref for ExternalEndpoint {
}
}
/// Build an `IssueFilter` by reading the project from the endpoint's
/// `OperationVc<OptionEndpoint>` and extracting ignore rules from its config.
async fn issue_filter_from_endpoint(
endpoint_op: OperationVc<OptionEndpoint>,
) -> Result<Vc<IssueFilter>> {
let endpoint_option = endpoint_op.connect().await?;
if let Some(ep) = &*endpoint_option {
Ok(ep.project().issue_filter())
} else {
Ok(IssueFilter::warnings_and_foreign_errors().cell())
}
}
#[turbo_tasks::value(serialization = "none")]
struct WrittenEndpointWithIssues {
written: Option<ReadRef<EndpointOutputPaths>>,
......@@ -111,8 +127,9 @@ async fn get_written_endpoint_with_issues_operation(
endpoint_op: OperationVc<OptionEndpoint>,
) -> Result<Vc<WrittenEndpointWithIssues>> {
let write_to_disk_op = endpoint_write_to_disk_operation(endpoint_op);
let filter = issue_filter_from_endpoint(endpoint_op).await?;
let (written, issues, diagnostics, effects) =
strongly_consistent_catch_collectables(write_to_disk_op).await?;
strongly_consistent_catch_collectables(write_to_disk_op, filter).await?;
Ok(WrittenEndpointWithIssues {
written,
issues,
......@@ -226,8 +243,9 @@ async fn subscribe_issues_and_diags_operation(
let changed_op = endpoint_server_changed_operation(endpoint_op);
if should_include_issues {
let filter = issue_filter_from_endpoint(endpoint_op).await?;
let (changed_value, issues, diagnostics, effects) =
strongly_consistent_catch_collectables(changed_op).await?;
strongly_consistent_catch_collectables(changed_op, filter).await?;
Ok(EndpointIssuesAndDiags {
changed: changed_value,
issues,
......
......@@ -87,9 +87,10 @@ static SOURCE_MAP_PREFIX: Lazy<String> = Lazy::new(|| format!("{SOURCE_URL_PROTO
static SOURCE_MAP_PREFIX_PROJECT: Lazy<String> =
Lazy::new(|| format!("{SOURCE_URL_PROTOCOL}///[{PROJECT_FILESYSTEM_NAME}]/"));
/// Next doesn't display warnings from node_modules, so configure turbopack to not report them
/// either. This matches logic in `packages/next/src/server/dev/turbopack-utils.ts`
pub const NEXT_ISSUE_FILTER: IssueFilter = IssueFilter::warnings_and_foreign_errors();
/// Get the `Vc<IssueFilter>` for a `ProjectContainer`.
fn issue_filter_from_container(container: ResolvedVc<ProjectContainer>) -> Vc<IssueFilter> {
container.project().issue_filter()
}
#[napi(object)]
#[derive(Clone, Debug)]
......@@ -945,8 +946,9 @@ async fn get_entrypoints_with_issues_operation(
) -> Result<Vc<EntrypointsWithIssues>> {
let entrypoints_operation =
EntrypointsOperation::new(project_container_entrypoints_operation(container));
let filter = issue_filter_from_container(container);
let (entrypoints, issues, diagnostics, effects) =
strongly_consistent_catch_collectables(entrypoints_operation).await?;
strongly_consistent_catch_collectables(entrypoints_operation, filter).await?;
Ok(EntrypointsWithIssues {
entrypoints,
issues,
......@@ -1043,8 +1045,9 @@ async fn get_all_written_entrypoints_with_issues_operation(
container,
app_dir_only,
));
let filter = issue_filter_from_container(container);
let (entrypoints, issues, diagnostics, effects) =
strongly_consistent_catch_collectables(entrypoints_operation).await?;
strongly_consistent_catch_collectables(entrypoints_operation, filter).await?;
Ok(AllWrittenEntrypointsWithIssues {
entrypoints,
issues,
......@@ -1224,7 +1227,8 @@ async fn hmr_update_with_issues_operation(
) -> Result<Vc<HmrUpdateWithIssues>> {
let update_op = project_hmr_update_operation(project, chunk_name, target, state);
let update = update_op.read_strongly_consistent().await?;
let issues = get_issues(update_op, NEXT_ISSUE_FILTER).await?;
let filter = project.issue_filter();
let issues = get_issues(update_op, filter).await?;
let diagnostics = get_diagnostics(update_op).await?;
let effects = Arc::new(get_effects(update_op).await?);
Ok(HmrUpdateWithIssues {
......@@ -1358,7 +1362,8 @@ async fn get_hmr_chunk_names_with_issues_operation(
) -> Result<Vc<HmrChunkNamesWithIssues>> {
let hmr_chunk_names_op = project_hmr_chunk_names_operation(container, target);
let hmr_chunk_names = hmr_chunk_names_op.read_strongly_consistent().await?;
let issues = get_issues(hmr_chunk_names_op, NEXT_ISSUE_FILTER).await?;
let filter = issue_filter_from_container(container);
let issues = get_issues(hmr_chunk_names_op, filter).await?;
let diagnostics = get_diagnostics(hmr_chunk_names_op).await?;
let effects = Arc::new(get_effects(hmr_chunk_names_op).await?);
Ok(HmrChunkNamesWithIssues {
......
......@@ -23,7 +23,7 @@ use turbopack_core::{
source_pos::SourcePos,
};
use crate::next_api::{project::NEXT_ISSUE_FILTER, turbopack_ctx::NextTurbopackContext};
use crate::next_api::turbopack_ctx::NextTurbopackContext;
/// An [`OperationVc`] that can be passed back and forth to JS across the [`napi`][mod@napi]
/// boundary via [`External`].
......@@ -97,7 +97,7 @@ pub fn root_task_dispose(
pub async fn get_issues<T: Send>(
source: OperationVc<T>,
filter: IssueFilter,
filter: Vc<IssueFilter>,
) -> Result<Arc<Vec<ReadRef<PlainIssue>>>> {
Ok(Arc::new(
source.peek_issues().get_plain_issues(filter).await?,
......@@ -360,6 +360,7 @@ pub fn subscribe<T: 'static + Send + Sync, F: Future<Output = Result<T>> + Send,
// propagate any actual error results.
pub async fn strongly_consistent_catch_collectables<R: VcValueType + Send>(
source_op: OperationVc<R>,
filter: Vc<IssueFilter>,
) -> Result<(
Option<ReadRef<R>>,
Arc<Vec<ReadRef<PlainIssue>>>,
......@@ -367,7 +368,7 @@ pub async fn strongly_consistent_catch_collectables<R: VcValueType + Send>(
Arc<Effects>,
)> {
let result = source_op.read_strongly_consistent().await;
let issues = get_issues(source_op, NEXT_ISSUE_FILTER).await?;
let issues = get_issues(source_op, filter).await?;
let diagnostics = get_diagnostics(source_op).await?;
let effects = Arc::new(get_effects(source_op).await?);
......
---
title: turbopackIgnoreIssue
description: Suppress specific Turbopack errors and warnings from the CLI output and error overlay.
version: experimental
related:
title: Next Steps
description: Learn more about Turbopack configuration.
links:
- app/api-reference/config/next-config-js/turbopack
- app/api-reference/turbopack
---
The `turbopackIgnoreIssue` option allows you to filter out specific [Turbopack](/docs/app/api-reference/turbopack) errors and warnings so they do not appear in the CLI output or the error overlay. This is useful for suppressing known warnings that do not affect your application, such as intentionally unresolved optional dependencies.
This option is only available when using Turbopack (`next dev --turbopack`).
## Usage
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
turbopackIgnoreIssue: [
{
path: '**/vendor/**',
},
],
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
turbopackIgnoreIssue: [
{
path: '**/vendor/**',
},
],
},
}
module.exports = nextConfig
```
## Options
Each rule in the `turbopackIgnoreIssue` array is an object with the following fields:
| Field | Type | Required | Description |
| ----------------------------- | ------------------ | -------- | ------------------------------------------ |
| [`path`](#path) | `string \| RegExp` | Yes | Matches against the file path of the issue |
| [`title`](#title) | `string \| RegExp` | No | Matches against the issue title |
| [`description`](#description) | `string \| RegExp` | No | Matches against the issue description |
An issue is suppressed when it matches the `path` **and** all other specified fields in a rule. If only `path` is provided, any issue from a matching file is suppressed.
> **Good to know:** Issue titles and descriptions may change between Turbopack versions. The `path` field is generally stable, but is not guaranteed to remain consistent for all issue types. When possible, prefer using `path` patterns over `title` or `description` matching.
### `path`
A **glob pattern** (when a string) or **regular expression** that matches against the file path where the issue originated.
```js filename="next.config.js"
module.exports = {
experimental: {
turbopackIgnoreIssue: [
// Glob pattern: suppress issues from any file under vendor/
{ path: '**/vendor/**' },
// RegExp: suppress issues from files matching a pattern
{ path: /node_modules\/legacy-lib/ },
],
},
}
```
### `title`
An **exact string match** (when a string) or **regular expression** that matches against the issue title.
```js filename="next.config.js"
module.exports = {
experimental: {
turbopackIgnoreIssue: [
{
path: '**/src/**',
title: 'Module not found',
},
],
},
}
```
### `description`
An **exact string match** (when a string) or **regular expression** that matches against the issue description.
```js filename="next.config.js"
module.exports = {
experimental: {
turbopackIgnoreIssue: [
{
path: '**/src/**',
description: /Cannot find module 'optional-dep'/,
},
],
},
}
```
## Examples
### Suppressing warnings for optional dependencies
If your code uses `try/catch` around an optional `require()` call, Turbopack may report a "Module not found" warning. You can suppress it:
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
turbopackIgnoreIssue: [
{
path: '**/lib/optional-feature/**',
title: 'Module not found',
},
],
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
turbopackIgnoreIssue: [
{
path: '**/lib/optional-feature/**',
title: 'Module not found',
},
],
},
}
module.exports = nextConfig
```
### Combining multiple rules
You can specify multiple rules to suppress different issues:
```js filename="next.config.js"
module.exports = {
experimental: {
turbopackIgnoreIssue: [
{ path: '**/vendor/**' },
{ path: '**/legacy/**', title: 'Module not found' },
{ path: /generated\//, description: /expected identifier/ },
],
},
}
```
## Version History
| Version | Changes |
| --------- | ---------------------------------- |
| `v16.2.0` | `turbopackIgnoreIssue` introduced. |
......@@ -233,6 +233,28 @@ Turbopack can be configured via `next.config.js` (or `next.config.ts`) under the
- **`resolveExtensions`**
Change or extend file extensions for module resolution.
Additionally, the following experimental options are available under `experimental` in `next.config.js`:
| Option | Description | Default (dev) | Default (build) |
| ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- | ------------- | ----------------------------- |
| [`turbopackFileSystemCacheForDev`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) | Enable filesystem cache for the dev server. | `true` | N/A |
| [`turbopackFileSystemCacheForBuild`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) | Enable filesystem cache for builds. | N/A | `false` |
| [`turbopackIgnoreIssue`](/docs/app/api-reference/config/next-config-js/turbopackIgnoreIssue) | Suppress specific Turbopack errors and warnings from the CLI output and error overlay. | `[]` | `[]` |
| `turbopackMinify` | Enable minification. | `false` | `true` |
| `turbopackSourceMaps` | Enable source maps. | `true` | `productionBrowserSourceMaps` |
| `turbopackInputSourceMaps` | Enable extraction of source maps from input files. | `true` | `true` |
| `turbopackTreeShaking` | Use advanced module-fragments tree shaking instead of the default reexports-only mode. | `false` | `false` |
| `turbopackRemoveUnusedImports` | Enable removing unused imports. Requires `turbopackRemoveUnusedExports`. | `false` | `true` |
| `turbopackRemoveUnusedExports` | Enable removing unused exports. | `false` | `true` |
| `turbopackInferModuleSideEffects` | Enable local analysis to infer side-effect-free modules for better tree shaking. | `true` | `true` |
| `turbopackScopeHoisting` | Enable scope hoisting. Always disabled in dev mode. | `false` | `true` |
| `turbopackClientSideNestedAsyncChunking` | Enable nested async chunking for client-side assets. | `false` | `true` |
| `turbopackServerSideNestedAsyncChunking` | Enable nested async chunking for server-side assets. | `false` | `false` |
| `turbopackImportTypeBytes` | Enable support for `with {type: "bytes"}` for ESM imports. | `false` | `false` |
| `turbopackUseBuiltinBabel` | Enable automatic Babel loader configuration when a Babel config file is present. | `true` | `true` |
| `turbopackUseBuiltinSass` | Enable automatic Sass loader configuration. | `true` | `true` |
| `turbopackModuleIds` | Module ID strategy: `'named'` or `'deterministic'`. | `'named'` | `'deterministic'` |
```js filename="next.config.js"
module.exports = {
turbopack: {
......
......@@ -965,6 +965,45 @@ function bindingToApi(
nextConfigSerializable.turbopack = turbopack
}
// Serialize turbopackIgnoreIssue rules: convert RegExp to {source, flags}
if (nextConfigSerializable.experimental?.turbopackIgnoreIssue) {
function serializePatternField(
value: string | RegExp,
stringType: 'glob' | 'string'
) {
if (value instanceof RegExp) {
return {
type: 'regex' as const,
source: value.source,
flags: value.flags,
}
}
return { type: stringType, value }
}
nextConfigSerializable.experimental = {
...nextConfigSerializable.experimental,
turbopackIgnoreIssue:
nextConfigSerializable.experimental.turbopackIgnoreIssue.map(
(rule: {
path: string | RegExp
title?: string | RegExp
description?: string | RegExp
}) => ({
path: serializePatternField(rule.path, 'glob'),
title:
rule.title != null
? serializePatternField(rule.title, 'string')
: undefined,
description:
rule.description != null
? serializePatternField(rule.description, 'string')
: undefined,
})
),
}
}
return JSON.stringify(nextConfigSerializable, null, 2)
}
......
......@@ -329,6 +329,15 @@ export const experimentalSchema = {
turbopackUseBuiltinSass: z.boolean().optional(),
turbopackModuleIds: z.enum(['named', 'deterministic']).optional(),
turbopackInferModuleSideEffects: z.boolean().optional(),
turbopackIgnoreIssue: z
.array(
z.object({
path: z.union([z.string(), z.instanceof(RegExp)]),
title: z.union([z.string(), z.instanceof(RegExp)]).optional(),
description: z.union([z.string(), z.instanceof(RegExp)]).optional(),
})
)
.optional(),
optimizePackageImports: z.array(z.string()).optional(),
optimizeServerReact: z.boolean().optional(),
strictRouteTypes: z.boolean().optional(),
......
......@@ -551,6 +551,19 @@ export interface ExperimentalConfig {
*/
turbopackInferModuleSideEffects?: boolean
/**
* An array of issue filter rules to ignore specific Turbopack issues.
* Each rule must have a `path` field (mandatory) and optionally `title`
* and `description`. String paths are treated as glob patterns. String
* titles/descriptions are exact matches. RegExp values match anywhere
* within the string (use `^` and `$` anchors for full-string matching).
*/
turbopackIgnoreIssue?: Array<{
path: string | RegExp
title?: string | RegExp
description?: string | RegExp
}>
/**
* 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.
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
if (Math.random() < 0) {
require('a-missing-module-for-route-error-testing')
}
export async function GET() {
return Response.json({ error: false })
}
export async function GET() {
let missing = null
try {
missing = require('a-missing-module-for-route-warning-testing')
} catch (e) {
// expected
}
return Response.json({ warning: true, missing: String(missing) })
}
if (Math.random() < 0) {
require('a-missing-module-for-server-error-testing')
}
export default function Page() {
return <p>server error page</p>
}
export default function Page() {
let missing = null
try {
missing = require('a-missing-module-for-server-warning-testing')
} catch (e) {
// expected
}
return <p>server warning page {String(missing)}</p>
}
'use client'
if (Math.random() < 0) {
require('a-missing-module-for-error-testing')
}
export default function Page() {
return <p>error page</p>
}
'use client'
export default function Page() {
let missing = null
try {
missing = require('a-missing-module-for-testing')
} catch (e) {
// expected
}
return <p>warning page {String(missing)}</p>
}
import { nextTestSetup } from 'e2e-utils'
import { retry, waitForNoRedbox, waitForRedbox } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
describe('turbopack-ignore-issue', () => {
describe('with turbopackIgnoreIssue config', () => {
const { next, skipped, isTurbopack } = nextTestSetup({
files: __dirname,
// turbopackIgnoreIssue is turbopack-only
skipDeployment: true,
nextConfig: {
experimental: {
turbopackIgnoreIssue: [
{
// glob string pattern for path
path: '**/with-warning/**',
},
{
path: '**/with-error/**',
},
{
path: '**/server-with-warning/**',
},
{
path: '**/server-with-error/**',
},
{
path: '**/route-with-warning/**',
},
{
path: '**/route-with-error/**',
},
],
},
},
})
if (skipped) return
if (!isTurbopack) {
it('should skip tests since turbopackIgnoreIssue only works with Turbopack', () => {})
return
}
it('should suppress ignored warning from cli output', async () => {
// Trigger compilation of the warning page
const outputIndex = next.cliOutput.length
await next.fetch('/with-warning')
// Wait for compilation to finish (the GET log line confirms the page
// was fully compiled and rendered).
await retry(async () => {
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).toContain('GET /with-warning')
})
// Now that compilation is complete, the warning should be absent
// because our turbopackIgnoreIssue rule matches the path.
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).not.toContain('a-missing-module-for-testing')
})
it('should suppress ignored error from error overlay', async () => {
// Navigate to the page with a top-level require of a missing module
// (outside try-catch), which normally produces an error shown in the
// error overlay.
const browser = await next.browser('/with-error')
await waitForNoRedbox(browser)
})
it('should suppress ignored server component warning from cli output', async () => {
const outputIndex = next.cliOutput.length
await next.fetch('/server-with-warning')
await retry(async () => {
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).toContain('GET /server-with-warning')
})
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).not.toContain(
'a-missing-module-for-server-warning-testing'
)
})
it('should suppress ignored server component error from error overlay', async () => {
const browser = await next.browser('/server-with-error')
await waitForNoRedbox(browser)
})
it('should suppress ignored route handler warning from cli output', async () => {
const outputIndex = next.cliOutput.length
await next.fetch('/route-with-warning')
await retry(async () => {
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).toContain('GET /route-with-warning')
})
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).not.toContain('a-missing-module-for-route-warning-testing')
})
it('should suppress ignored route handler error from cli output', async () => {
const outputIndex = next.cliOutput.length
await next.fetch('/route-with-error')
await retry(async () => {
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).toContain('GET /route-with-error')
})
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).not.toContain('a-missing-module-for-route-error-testing')
})
it('should still show issues for pages without ignore rules', async () => {
// The home page should compile normally without issues
const res = await next.fetch('/')
expect(res.status).toBe(200)
const html = await res.text()
expect(html).toContain('hello world')
})
})
describe('without turbopackIgnoreIssue config', () => {
const { next, skipped, isTurbopack } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
it('should show warning in cli output when not ignored', async () => {
// Trigger compilation of the warning page
const outputIndex = next.cliOutput.length
await next.fetch('/with-warning')
// The warning about 'a-missing-module-for-testing' should appear
// since there is no turbopackIgnoreIssue config
await retry(async () => {
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).toContain('a-missing-module-for-testing')
})
})
it('should show error in error overlay when not ignored', async () => {
if (!isTurbopack) {
// turbopackIgnoreIssue only works with Turbopack
return
}
// Navigate to the page with a top-level require of a missing module.
// Without turbopackIgnoreIssue, the error should appear in the overlay.
const browser = await next.browser('/with-error')
await waitForRedbox(browser)
})
it('should show server component warning in cli output when not ignored', async () => {
const outputIndex = next.cliOutput.length
await next.fetch('/server-with-warning')
await retry(async () => {
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).toContain('a-missing-module-for-server-warning-testing')
})
})
it('should show server component error in error overlay when not ignored', async () => {
if (!isTurbopack) {
return
}
const browser = await next.browser('/server-with-error')
await waitForRedbox(browser)
})
it('should show route handler warning in cli output when not ignored', async () => {
const outputIndex = next.cliOutput.length
await next.fetch('/route-with-warning')
await retry(async () => {
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).toContain('a-missing-module-for-route-warning-testing')
})
})
it('should show route handler error in cli output when not ignored', async () => {
if (!isTurbopack) {
return
}
const outputIndex = next.cliOutput.length
await next.fetch('/route-with-error')
await retry(async () => {
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).toContain('a-missing-module-for-route-error-testing')
})
})
})
})
......@@ -6,6 +6,7 @@ use bincode::{
de::Decoder,
enc::Encoder,
error::{DecodeError, EncodeError},
impl_borrow_decode,
};
use regex::bytes::{Regex, RegexBuilder};
use turbo_rcstr::{RcStr, rcstr};
......@@ -67,6 +68,8 @@ impl<Context> Decode<Context> for Glob {
}
}
impl_borrow_decode!(Glob);
#[derive(
Copy, Clone, PartialEq, Eq, Hash, Default, TaskInput, TraceRawVcs, Debug, Encode, Decode,
)]
......
......@@ -38,6 +38,7 @@ swc_sourcemap = { workspace = true }
swc_core = { workspace = true, features = ["ecma_preset_env", "common"] }
tracing = { workspace = true }
turbo-bincode = { workspace = true }
turbo-esregex = { workspace = true }
turbo-frozenmap = { workspace = true }
turbo-prehash = { workspace = true }
turbo-rcstr = { workspace = true }
......
......@@ -12,13 +12,16 @@ use anyhow::{Result, anyhow};
use auto_hash_map::AutoSet;
use bincode::{Decode, Encode};
use serde::{Deserialize, Serialize};
use turbo_esregex::EsRegex;
use turbo_rcstr::RcStr;
use turbo_tasks::{
CollectiblesSource, IntoTraitRef, NonLocalValue, OperationVc, RawVc, ReadRef, ResolvedVc,
TaskInput, TransientValue, TryFlatJoinIterExt, TryJoinIterExt, Upcast, ValueDefault,
ValueToString, Vc, emit, trace::TraceRawVcs,
};
use turbo_tasks_fs::{FileContent, FileLine, FileLinesContent, FileSystem, FileSystemPath};
use turbo_tasks_fs::{
FileContent, FileLine, FileLinesContent, FileSystem, FileSystemPath, glob::Glob,
};
use turbo_tasks_hash::{DeterministicHash, Xxh3Hash64Hasher};
use crate::{
......@@ -235,56 +238,159 @@ where
#[turbo_tasks::value(transparent)]
pub struct Issues(Vec<ResolvedVc<Box<dyn Issue>>>);
#[derive(TaskInput, Hash, Eq, PartialEq, Copy, Clone, Encode, Decode, TraceRawVcs, Debug)]
/// A pattern that can match by exact string, glob, or regex.
#[derive(Clone, Debug, PartialEq, Eq, TraceRawVcs, NonLocalValue, Encode, Decode)]
pub enum IgnoreIssuePattern {
/// The value must exactly equal the pattern string.
ExactString(RcStr),
/// The pattern is treated as a glob (uses turbo-tasks-fs glob matching).
Glob(Glob),
/// The pattern is a regular expression (supports ES-style patterns via `EsRegex`).
Regex(EsRegex),
}
impl IgnoreIssuePattern {
/// Test whether the pattern matches the given value.
pub fn matches(&self, value: &str) -> bool {
match self {
IgnoreIssuePattern::ExactString(s) => value == s.as_str(),
IgnoreIssuePattern::Glob(glob) => glob.matches(value),
IgnoreIssuePattern::Regex(regex) => regex.is_match(value),
}
}
}
/// A rule describing an issue to ignore. `path` is mandatory;
/// `title` and `description` are optional additional filters.
#[derive(Clone, Debug, PartialEq, Eq, TraceRawVcs, NonLocalValue, Encode, Decode)]
pub struct IgnoreIssue {
/// File-path pattern (mandatory).
pub path: IgnoreIssuePattern,
/// Title pattern (optional).
pub title: Option<IgnoreIssuePattern>,
/// Description pattern (optional).
pub description: Option<IgnoreIssuePattern>,
}
#[turbo_tasks::value(shared)]
pub struct IssueFilter {
/// The minimum severity for issues
severity: IssueSeverity,
/// The minimum severity for issues in node_modules
foreign_severity: IssueSeverity,
/// Issues matching any of these rules are ignored (dropped from results).
ignore_rules: Vec<IgnoreIssue>,
}
#[turbo_tasks::value_impl]
impl IssueFilter {
pub const fn everything() -> Self {
Self {
/// A filter that lets everything through.
#[turbo_tasks::function]
pub fn everything() -> Vc<Self> {
IssueFilter {
severity: IssueSeverity::Info,
foreign_severity: IssueSeverity::Info,
ignore_rules: Vec::new(),
}
.cell()
}
pub const fn warnings_and_foreign_errors() -> Self {
Self {
severity: IssueSeverity::Warning,
foreign_severity: IssueSeverity::Error,
/// Returns true if the issue is allowed by this filter.
#[turbo_tasks::function]
pub async fn matches(&self, issue: ResolvedVc<Box<dyn Issue>>) -> Result<Vc<bool>> {
let has_no_ignore_rules = self.ignore_rules.is_empty();
let is_everything = self.severity == IssueSeverity::Info
&& self.foreign_severity == IssueSeverity::Info
&& has_no_ignore_rules;
if is_everything {
return Ok(Vc::cell(true));
}
}
/// Returns true if the issue is allowed by this filter. issue
async fn matches(&self, issue: ResolvedVc<Box<dyn Issue>>) -> Result<bool> {
if *self == IssueFilter::everything() {
return Ok(true);
}
// Fetch the file path once — it's used by both severity and ignore-rule
// checks.
let file_path = issue.file_path().await?;
// Check severity first — this is cheap and avoids fetching
// title/description for issues that would be filtered out anyway.
let severity = issue.into_trait_ref().await?.severity();
// NOTE: Lower severities are _more_ severe
Ok(
if severity <= self.severity || severity <= self.foreign_severity {
// we need to check the path to see if it is foreign or not. Only await the path if
// it might possibly matter
if severity <= self.severity && severity <= self.foreign_severity {
// it matches no matter where the path is
true
} else {
let path = issue.file_path().await?;
if ContextCondition::InNodeModules.matches(&path) {
severity <= self.foreign_severity
} else {
severity <= self.severity
let severity_allowed = if severity <= self.severity || severity <= self.foreign_severity {
// we need to check the path to see if it is foreign or not. Only await the
// path if it might possibly matter
if severity <= self.severity && severity <= self.foreign_severity {
// it matches no matter where the path is
true
} else if ContextCondition::InNodeModules.matches(&file_path) {
severity <= self.foreign_severity
} else {
severity <= self.severity
}
} else {
// it is too low severity to match either way
false
};
if !severity_allowed {
return Ok(Vc::cell(false));
}
// Check ignore rules — if any rule matches, the issue is dropped.
// Title and description are fetched lazily: only when a rule's path
// matches and the rule also specifies a title/description pattern.
if !has_no_ignore_rules {
let file_path_str = file_path.to_string();
let mut title_str: Option<String> = None;
let mut description_text: Option<Option<String>> = None;
for rule in &self.ignore_rules {
if !rule.path.matches(&file_path_str) {
continue;
}
if let Some(ref title_pat) = rule.title {
if title_str.is_none() {
title_str = Some(issue.title().await?.to_unstyled_string());
}
if !title_pat.matches(title_str.as_deref().unwrap()) {
continue;
}
}
} else {
// it is too low severity to match either way
false
},
)
if let Some(ref desc_pat) = rule.description {
if description_text.is_none() {
let desc_opt = issue.description().await?;
description_text = Some(match desc_opt.as_ref() {
Some(desc_vc) => Some(desc_vc.await?.to_unstyled_string()),
None => None,
});
}
match description_text.as_ref().unwrap().as_deref() {
Some(desc) if desc_pat.matches(desc) => {}
_ => continue,
}
}
// All specified fields matched — ignore this issue.
return Ok(Vc::cell(false));
}
}
Ok(Vc::cell(true))
}
}
impl IssueFilter {
/// Construct a filter with the standard warning/foreign-error severities.
pub fn warnings_and_foreign_errors() -> Self {
IssueFilter {
severity: IssueSeverity::Warning,
foreign_severity: IssueSeverity::Error,
ignore_rules: Vec::new(),
}
}
/// Set the ignore rules for this filter.
pub fn with_ignore_rules(mut self, rules: Vec<IgnoreIssue>) -> Self {
self.ignore_rules = rules;
self
}
}
......@@ -323,12 +429,15 @@ impl CapturedIssues {
}
// Returns all the issues as formatted `PlainIssues`.
pub async fn get_plain_issues(&self, filter: IssueFilter) -> Result<Vec<ReadRef<PlainIssue>>> {
pub async fn get_plain_issues(
&self,
filter: Vc<IssueFilter>,
) -> Result<Vec<ReadRef<PlainIssue>>> {
let mut list = self
.issues
.iter()
.map(async |issue| {
if filter.matches(*issue).await? {
if *filter.matches(**issue).await? {
Ok(Some(
PlainIssue::from_issue(**issue, Some(*self.tracer)).await?,
))
......
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