Skip to content

Turbopack: cross-module constants#90300

Open
mischnic wants to merge 47 commits intocanaryfrom
mischnic/cross-module-constants
Open

Turbopack: cross-module constants#90300
mischnic wants to merge 47 commits intocanaryfrom
mischnic/cross-module-constants

Conversation

@mischnic
Copy link
Member

@mischnic mischnic commented Feb 21, 2026

This is now a proper compile-time constant:

import { IS_DEV } from './other'
if (IS_DEV) { // statically evaluates to `true`
  console.log('x')
} else {
  require("library") // not bundled
}
console.log(IS_DEV); // is replaced with console.log(true);
// other.ts
export const SOME_VALUE = 'x'

const node_env = process.env.NODE_ENV
const development_ent = 'development'
export const IS_DEV = node_env === development_ent

You can use code to compute constants just fine, and use any existing constants such as process.env.NODE_ENV.
Currently, you can't use imports to other constants modules, but we can add that later on.

We can't perform this constants check for every single import, so you need to either

  • have UPPER_CASE import names as in the example above
  • or use import { lower } from './other' with { turbopackConstants: 'true' }

Then that referenced module will be analyzed for constants, and if the referenced export is a constant, it will participate in constant inlining just as process.env.FOO.

This also works fine with barrel imports, you can still do import { IS_DEV } from './barrel.js' and it will find the constants.js file which in itself will indeed only have constants exports.

Because it's not always opt-in at the import site, we can't automatically make non-constant exports an error. For that you have to add 'use turbopack constants' at the top of the module, which will make it an error if any constant import references that module, and the module has any non-constant exports:

error - [analysis] /turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module/input/other.constants.js:8:7 
Export NO_CONSTANT is not a constant
  
       4 | const development_ent = 'development'
       5 | 
       6 | export const IS_DEV = node_env === development_ent
       7 | 
         +        v--------------------------------v
       8 + export const NO_CONSTANT = globalThis.foo
         +        ^--------------------------------^
       9 | 
  
  It was analyzed to be FreeVar(globalThis)["foo"]
  
  
  Import trace:
    test:
      ./turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module/input/other.constants.js
      ./turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module/input/index.js

Some prior art: https://rspack.rs/blog/announcing-1-5#const-inline-optimization, https://rspack.rs/config/optimization#optimizationinlineexports

No compile-time impact on a big app:

canary dfbc3dc6b7: 
438.11s user, 68.35s system, 801% cpu, 1:03.22 total
439.44s user, 71.47s system, 756% cpu, 1:07.56 total
440.32s user, 68.57s system, 750% cpu, 1:07.81 total

constants 2d7eb8220d298133212813b7267a5847eed03a22
433.22s user, 65.44s system, 800% cpu, 1:02.32 total
440.52s user, 67.68s system, 770% cpu, 1:05.95 total
433.13s user, 69.47s system, 776% cpu, 1:04.74 total

@nextjs-bot nextjs-bot added created-by: Turbopack team PRs by the Turbopack team. Turbopack Related to Turbopack with Next.js. labels Feb 21, 2026
Copy link
Member Author

mischnic commented Feb 21, 2026

This stack of pull requests is managed by Graphite. Learn more about stacking.

@mischnic mischnic force-pushed the mischnic/cross-module-constants branch from 89cc65e to 24998d4 Compare February 21, 2026 14:04
@codspeed-hq
Copy link

codspeed-hq bot commented Feb 21, 2026

Merging this PR will degrade performance by 8.56%

❌ 8 regressed benchmarks
✅ 9 untouched benchmarks
⏩ 3 skipped benchmarks1

⚠️ Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Mode Benchmark BASE HEAD Efficiency
Simulation packages-bundle.js[full] 1.2 s 1.3 s -5.68%
Simulation jsonwebtoken.js[full] 371.8 ms 406.6 ms -8.55%
Simulation packages-bundle.js[tracing] 1 s 1.1 s -5.78%
Simulation app-page-turbo.runtime.prod.js[full] 784.2 ms 832.3 ms -5.78%
Simulation react-dom-client.development.js[full] 509.2 ms 551.8 ms -7.72%
Simulation react-dom-client.development.js[tracing] 441.5 ms 476.4 ms -7.33%
Simulation jsonwebtoken.js[tracing] 324.8 ms 355.2 ms -8.56%
Simulation app-page-turbo.runtime.prod.js[tracing] 664.1 ms 706.1 ms -5.95%

Comparing mischnic/cross-module-constants (6887358) with canary (b7b58b2)

Open in CodSpeed

Footnotes

  1. 3 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

@nextjs-bot
Copy link
Collaborator

nextjs-bot commented Feb 21, 2026

Stats from current PR

✅ No significant changes detected

📊 All Metrics
📖 Metrics Glossary

Dev Server Metrics:

  • Listen = TCP port starts accepting connections
  • First Request = HTTP server returns successful response
  • Cold = Fresh build (no cache)
  • Warm = With cached build artifacts

Build Metrics:

  • Fresh = Clean build (no .next directory)
  • Cached = With existing .next directory

Change Thresholds:

  • Time: Changes < 50ms AND < 10%, OR < 2% are insignificant
  • Size: Changes < 1KB AND < 1% are insignificant
  • All other changes are flagged to catch regressions

⚡ Dev Server

Metric Canary PR Change Trend
Cold (Listen) 455ms 455ms ▁▇▇▁▁
Cold (Ready in log) 435ms 436ms ▂▇▇▂▁
Cold (First Request) 1.215s 1.215s ▃▇▇▄▂
Warm (Listen) 456ms 457ms ▁▇▇▁▁
Warm (Ready in log) 438ms 440ms ▁▆▆▁▁
Warm (First Request) 347ms 348ms ▁▆▆▂▂
📦 Dev Server (Webpack) (Legacy)

📦 Dev Server (Webpack)

Metric Canary PR Change Trend
Cold (Listen) 456ms 455ms ▁▁▁▁█
Cold (Ready in log) 435ms 434ms ▅▂▅▆█
Cold (First Request) 1.841s 1.833s ▄▁▄▄█
Warm (Listen) 456ms 455ms ▁▁▁▁█
Warm (Ready in log) 435ms 435ms ▅▂▄▅█
Warm (First Request) 1.843s 1.881s ▄▁▄▄█

⚡ Production Builds

Metric Canary PR Change Trend
Fresh Build 3.707s 3.825s ▁▆▆▁▃
Cached Build 3.792s 3.797s ▁▆▆▁▃
📦 Production Builds (Webpack) (Legacy)

📦 Production Builds (Webpack)

Metric Canary PR Change Trend
Fresh Build 13.842s 13.791s ▁▁▂▂█
Cached Build 13.984s 13.996s ▁▁▁▂█
node_modules Size 476 MB 476 MB ▁▁▁▁▁
📦 Bundle Sizes

Bundle Sizes

⚡ Turbopack

Client

Main Bundles: **401 kB** → **401 kB** ✅ -14 B

80 files with content-based hashes (individual files not comparable between builds)

Server

Middleware
Canary PR Change
middleware-b..fest.js gzip 767 B 764 B
Total 767 B 764 B ✅ -3 B
Build Details
Build Manifests
Canary PR Change
_buildManifest.js gzip 450 B 452 B
Total 450 B 452 B ⚠️ +2 B

📦 Webpack

Client

Main Bundles
Canary PR Change
5528-HASH.js gzip 5.54 kB N/A -
6280-HASH.js gzip 59.4 kB N/A -
6335.HASH.js gzip 169 B N/A -
912-HASH.js gzip 4.59 kB N/A -
e8aec2e4-HASH.js gzip 62.6 kB N/A -
framework-HASH.js gzip 59.7 kB 59.7 kB
main-app-HASH.js gzip 256 B 254 B
main-HASH.js gzip 39.1 kB 39.1 kB
webpack-HASH.js gzip 1.68 kB 1.68 kB
262-HASH.js gzip N/A 4.59 kB -
2889.HASH.js gzip N/A 169 B -
5602-HASH.js gzip N/A 5.55 kB -
6948ada0-HASH.js gzip N/A 62.6 kB -
9544-HASH.js gzip N/A 60.2 kB -
Total 233 kB 234 kB ⚠️ +733 B
Polyfills
Canary PR Change
polyfills-HASH.js gzip 39.4 kB 39.4 kB
Total 39.4 kB 39.4 kB
Pages
Canary PR Change
_app-HASH.js gzip 194 B 194 B
_error-HASH.js gzip 183 B 180 B 🟢 3 B (-2%)
css-HASH.js gzip 331 B 330 B
dynamic-HASH.js gzip 1.81 kB 1.81 kB
edge-ssr-HASH.js gzip 256 B 256 B
head-HASH.js gzip 351 B 352 B
hooks-HASH.js gzip 384 B 383 B
image-HASH.js gzip 580 B 581 B
index-HASH.js gzip 260 B 260 B
link-HASH.js gzip 2.51 kB 2.51 kB
routerDirect..HASH.js gzip 320 B 319 B
script-HASH.js gzip 386 B 386 B
withRouter-HASH.js gzip 315 B 315 B
1afbb74e6ecf..834.css gzip 106 B 106 B
Total 7.98 kB 7.98 kB ✅ -1 B

Server

Edge SSR
Canary PR Change
edge-ssr.js gzip 125 kB 125 kB
page.js gzip 254 kB 254 kB
Total 378 kB 379 kB ⚠️ +513 B
Middleware
Canary PR Change
middleware-b..fest.js gzip 617 B 614 B
middleware-r..fest.js gzip 156 B 155 B
middleware.js gzip 43.5 kB 43.4 kB
edge-runtime..pack.js gzip 842 B 842 B
Total 45.2 kB 45.1 kB ✅ -106 B
Build Details
Build Manifests
Canary PR Change
_buildManifest.js gzip 715 B 718 B
Total 715 B 718 B ⚠️ +3 B
Build Cache
Canary PR Change
0.pack gzip 4.04 MB 4.05 MB 🔴 +8.56 kB (+0%)
index.pack gzip 102 kB 103 kB
index.pack.old gzip 103 kB 104 kB
Total 4.24 MB 4.25 MB ⚠️ +9.91 kB

🔄 Shared (bundler-independent)

Runtimes
Canary PR Change
app-page-exp...dev.js gzip 321 kB 321 kB
app-page-exp..prod.js gzip 170 kB 170 kB
app-page-tur...dev.js gzip 321 kB 321 kB
app-page-tur..prod.js gzip 170 kB 170 kB
app-page-tur...dev.js gzip 318 kB 318 kB
app-page-tur..prod.js gzip 168 kB 168 kB
app-page.run...dev.js gzip 318 kB 318 kB
app-page.run..prod.js gzip 168 kB 168 kB
app-route-ex...dev.js gzip 70.3 kB 70.3 kB
app-route-ex..prod.js gzip 48.6 kB 48.6 kB
app-route-tu...dev.js gzip 70.4 kB 70.4 kB
app-route-tu..prod.js gzip 48.7 kB 48.7 kB
app-route-tu...dev.js gzip 69.9 kB 69.9 kB
app-route-tu..prod.js gzip 48.4 kB 48.4 kB
app-route.ru...dev.js gzip 69.9 kB 69.9 kB
app-route.ru..prod.js gzip 48.4 kB 48.4 kB
dist_client_...dev.js gzip 324 B 324 B
dist_client_...dev.js gzip 326 B 326 B
dist_client_...dev.js gzip 318 B 318 B
dist_client_...dev.js gzip 317 B 317 B
pages-api-tu...dev.js gzip 43.2 kB 43.2 kB
pages-api-tu..prod.js gzip 32.9 kB 32.9 kB
pages-api.ru...dev.js gzip 43.2 kB 43.2 kB
pages-api.ru..prod.js gzip 32.9 kB 32.9 kB
pages-turbo....dev.js gzip 52.6 kB 52.6 kB
pages-turbo...prod.js gzip 38.5 kB 38.5 kB
pages.runtim...dev.js gzip 52.6 kB 52.6 kB
pages.runtim..prod.js gzip 38.5 kB 38.5 kB
server.runti..prod.js gzip 61.8 kB 61.8 kB
Total 2.83 MB 2.83 MB ⚠️ +2 B
📎 Tarball URL
https://vercel-packages.vercel.app/next/commits/d0cdf6d1db660379de8113d4870cf386731cbfca/next

@mischnic mischnic force-pushed the mischnic/cross-module-constants branch from 24998d4 to c23f620 Compare February 22, 2026 10:18
@cobm713

This comment was marked as spam.

@nextjs-bot
Copy link
Collaborator

nextjs-bot commented Feb 22, 2026

Failing test suites

Commit: 6887358 | About building and testing Next.js

pnpm test-dev test/e2e/app-dir/navigation/navigation.test.ts (job)

  • app dir - navigation > middleware redirect > should change browser location when router.refresh() gets a redirect response (DD)
Expand output

● app dir - navigation › middleware redirect › should change browser location when router.refresh() gets a redirect response

expect(received).toBe(expected) // Object.is equality

Expected: "http://localhost:46293/redirect-on-refresh/dashboard"
Received: "http://localhost:46293/redirect-on-refresh/auth"

  955 |       const browser = await next.browser('/redirect-on-refresh/auth')
  956 |       await retry(async () =>
> 957 |         expect(await browser.url()).toBe(
      |                                     ^
  958 |           next.url + '/redirect-on-refresh/dashboard'
  959 |         )
  960 |       )

  at toBe (e2e/app-dir/navigation/navigation.test.ts:957:37)
  at retry (lib/next-test-utils.ts:861:14)
  at Object.<anonymous> (e2e/app-dir/navigation/navigation.test.ts:956:7)

@mischnic mischnic force-pushed the mischnic/cross-module-constants branch from 2d09473 to 064c91d Compare February 22, 2026 11:20
@mischnic mischnic force-pushed the mischnic/cross-module-constants branch from 064c91d to 4ad9df0 Compare February 27, 2026 11:52
@mischnic mischnic force-pushed the mischnic/cross-module-constants branch 4 times, most recently from 06e4aff to 236f004 Compare February 27, 2026 21:44
@mischnic mischnic force-pushed the mischnic/cross-module-constants branch 3 times, most recently from 15c0416 to 2d7eb82 Compare March 5, 2026 11:07
@mischnic mischnic marked this pull request as ready for review March 5, 2026 11:57
@mischnic mischnic requested a review from sokra March 5, 2026 11:57
Comment on lines +56 to +84
// TODO this is missing all source transforms (e.g. Webpakc loaders)
//
// TODO ideally we'd use `import_reference[i].resolve_reference().first().failsafe_parse()` for
// determining the constants.
//
// That slots nicely into the module system (custom modules could participate in this together
// with Webpack loaders), and you get side-effect-free barrel file optimization for free). The
// problem is that `resolve_reference`` creates all the tree shaking modules, for which we need
// the exports of the module, which analyzes the module, which potentially analyzes
// cross-module constants, leading to the execution cycle.
//
// That cycle would ideally to be broken somehow.
let source = esm_resolve_source(
origin,
Request::parse_string(module_value.module.to_string_lossy().into()),
EcmaScriptModulesReferenceSubType::Import,
ResolveErrorMode::Ignore,
None,
)
.await?
.await?;

let Some(ResolveResultItem::Source(source)) = source.primary.first().as_ref().map(|v| &v.1)
else {
// failed to resolve, ignore silently
return Ok(None);
};

let constants = get_constants(**source, compile_time_info).await?;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is very broken and a blocker for enabling this by default. This could break stuff when source transforms are involved. And I can cause weird parse errors when source files depend on source transforms to be parseable.
It also caused files to be double parsed.
We need to change that.

I think it should be possible to make process not call analyze of modules. We do call get_exports, but that can a lightweight pass over the parsed module and not a full analyze. That would also be beneficial for side effect free module optimization when barrel files can be skipped without a full analyze step on them.

Comment on lines +113 to +142
JsValue::Constant(ConstantValue::Str(key.clone().into())),
if let Some(value) = value {
if !has_opt_in {
// when not having opt in, only inline short literals
match value {
ConstantValue::Str(s) if s.as_str().len() > 6 => {
JsValue::unknown_empty(false, "constant too long")
}
ConstantValue::Num(n) if n.0.abs() > 1_000_000.0 => {
JsValue::unknown_empty(false, "constant too long")
}
ConstantValue::BigInt(n)
if **n > BigInt::from(1_000_000)
|| **n < BigInt::from(-1_000_000) =>
{
JsValue::unknown_empty(false, "constant too long")
}
ConstantValue::Regex(_) => {
// Regexes are literals, but they are also objects, so
// have identity and aren't inlined without opt in.
JsValue::unknown_empty(false, "regex not inlined")
}
_ => JsValue::Constant(value.clone()),
}
} else {
JsValue::Constant(value.clone())
}
} else {
JsValue::unknown_empty(false, "not a constant")
},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would not expect this filtering to happen here.

I want to have compile-time values for everything,
but only inline values under certain conditions.

So I would expect the filtering happen in the inlining path.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All of this would be much easier if the link step were actually intelligent. As opposed to doing only bottom-up replacements.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But I think I can still achieve this somehow.

@mischnic mischnic changed the base branch from canary to graphite-base/90300 March 5, 2026 14:44
@mischnic mischnic force-pushed the mischnic/cross-module-constants branch from 0cce7f6 to 6887358 Compare March 7, 2026 11:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

created-by: Turbopack team PRs by the Turbopack team. Turbopack Related to Turbopack with Next.js.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants