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

Turbopack: Enable tree-shaking for dynamic imports with destructuring (#89683)

## What?

This PR enables tree-shaking for dynamic imports when the imported module's exports are destructured or accessed via member expressions. Previously, dynamic imports were treated as importing all exports, preventing unused exports from being removed.

## Why?

Dynamic imports with destructuring patterns like `const { cat } = await import('./lib')` or member access like `(await import('./lib')).cat` now properly communicate which specific exports are actually used. This allows bundlers (particularly Turbopack) to tree-shake unused exports from dynamically imported modules, reducing bundle size.

## How?

### Core Changes:

1. **AST Analysis Enhancement** (`turbopack-ecmascript/src/analyzer/graph.rs`):
   - Added new `Effect::DynamicImport` variant that captures destructuring patterns and member access
   - Implemented `extract_dynamic_import_export_names()` to statically analyze destructuring patterns and extract used export names
   - Supports: const/let/var destructuring, renamed imports, nested destructuring, default exports, member access, and empty destructuring

2. **Export Usage Tracking** (`turbopack-core/src/resolve/mod.rs`):
   - Added `ExportUsage::NamedSet` variant to track multiple named exports being used
   - Updated `ModuleExportUsageInfo` to handle merging of multiple named exports

3. **Dynamic Import Reference** (`turbopack-ecmascript/src/references/esm/dynamic.rs`):
   - Extended `EsmAsyncAssetReference` with `export_names` field
   - Implemented `binding_usage()` to communicate which exports are used to the module graph

4. **Effect Processing** (`turbopack-ecmascript/src/references/mod.rs`):
   - Refactored dynamic import handling into dedicated `handle_dynamic_import()` function
   - Passes export usage information through the reference system

### Test Coverage:

- **E2E Tests** (`test/e2e/app-dir/dynamic-import-tree-shaking/`): Comprehensive tests for Next.js App Router covering various destructuring patterns
- **Snapshot Tests** (`turbopack-tests/tests/snapshot/basic-tree-shake/`): Turbopack-specific tests validating tree-shaking behavior

### Supported Patterns:

- ✅ Named destructuring: `const { cat } = await import('./lib')`
- ✅ Variable declarations: `var`, `let`, `const`
- ✅ Renamed imports: `const { cat: myCat } = await import('./lib')`
- ✅ Nested destructuring: `const { dogRef: { get } } = await import('./lib')`
- ✅ Default exports: `const { default: val } = await import('./lib')`
- ✅ Empty destructuring: `const {} = await import('./lib')` (side effects only)
- ✅ Member access: `(await import('./lib')).cat`

### Limitations:

- Rest patterns (`const { cat, ...rest }`) conservatively import all exports
- Computed property keys are not statically analyzed
- Member access tree-shaking is Turbopack-only (webpack limitation)

https://claude.ai/code/session_01QWi3udq2LX4GFqJEDaqFFU
parent 5509e1bf
......@@ -23,7 +23,10 @@ struct NextTrackDynamicImports {}
impl CustomTransformer for NextTrackDynamicImports {
#[tracing::instrument(level = tracing::Level::TRACE, name = "next_track_dynamic_imports", skip_all)]
async fn transform(&self, program: &mut Program, ctx: &TransformContext<'_>) -> Result<()> {
program.mutate(track_dynamic_imports(ctx.unresolved_mark));
program.mutate(track_dynamic_imports(
ctx.unresolved_mark,
ctx.comments.clone(),
));
Ok(())
}
}
......@@ -329,6 +329,7 @@ where
true => Either::Left(
crate::transforms::track_dynamic_imports::track_dynamic_imports(
unresolved_mark,
comments.clone(),
),
),
false => Either::Right(noop_pass()),
......
use rustc_hash::FxHashMap;
use swc_core::{
common::{source_map::PURE_SP, util::take::Take, Mark, SyntaxContext},
common::{
comments::{Comment, CommentKind, Comments},
source_map::PURE_SP,
util::take::Take,
BytePos, Mark, Span, Spanned, SyntaxContext, DUMMY_SP,
},
ecma::{
ast::*,
utils::{prepend_stmt, private_ident, quote_ident, quote_str},
......@@ -8,27 +14,86 @@ use swc_core::{
quote,
};
pub fn track_dynamic_imports(unresolved_mark: Mark) -> impl VisitMut + Pass {
visit_mut_pass(ImportReplacer::new(unresolved_mark))
pub fn track_dynamic_imports<C: Comments>(
unresolved_mark: Mark,
comments: C,
) -> impl VisitMut + Pass {
visit_mut_pass(ImportReplacer::new(unresolved_mark, comments))
}
struct ImportReplacer {
struct ImportReplacer<C: Comments> {
comments: C,
unresolved_ctxt: SyntaxContext,
has_dynamic_import: bool,
wrapper_function_local_ident: Ident,
/// Maps import call span lo → export names extracted from destructuring
import_export_names: FxHashMap<BytePos, Vec<String>>,
}
impl ImportReplacer {
pub fn new(unresolved_mark: Mark) -> Self {
impl<C: Comments> ImportReplacer<C> {
pub fn new(unresolved_mark: Mark, comments: C) -> Self {
ImportReplacer {
comments,
unresolved_ctxt: SyntaxContext::empty().apply_mark(unresolved_mark),
has_dynamic_import: false,
wrapper_function_local_ident: private_ident!("$$trackDynamicImport__"),
import_export_names: Default::default(),
}
}
}
/// Try to find an `await import(...)` CallExpr inside an expression,
/// unwrapping parentheses. Returns the span of the import call only if
/// `await` is present — without await, the destructuring targets the
/// Promise, not the module namespace.
fn find_awaited_import_call_span(expr: &Expr) -> Option<Span> {
let mut current: &Expr = expr;
let mut seen_await = false;
loop {
match current {
Expr::Call(CallExpr {
callee: Callee::Import(_),
span,
..
}) if seen_await => {
break Some(*span);
}
Expr::Await(AwaitExpr { arg, .. }) => {
seen_await = true;
current = arg;
}
Expr::Paren(ParenExpr { expr, .. }) => {
current = expr;
}
_ => break None,
}
}
}
impl VisitMut for ImportReplacer {
/// Extract export names from an ObjectPattern (destructuring pattern).
/// Returns `Some(names)` for recognized patterns, `None` for patterns
/// that can't be statically analyzed (rest elements, computed keys).
fn extract_export_names_from_pat(pat: &ObjectPat) -> Option<Vec<String>> {
let mut names = Vec::new();
for prop in &pat.props {
match prop {
ObjectPatProp::KeyValue(KeyValuePatProp { key, .. }) => match key {
PropName::Ident(ident) => names.push(ident.sym.to_string()),
PropName::Str(s) => names.push(s.value.to_string_lossy().into_owned()),
// Computed keys can't be statically analyzed
_ => return None,
},
ObjectPatProp::Assign(AssignPatProp { key, .. }) => {
names.push(key.sym.to_string());
}
// Rest elements mean all exports are potentially used
ObjectPatProp::Rest(_) => return None,
}
}
Some(names)
}
impl<C: Comments> VisitMut for ImportReplacer<C> {
noop_visit_mut_type!();
fn visit_mut_program(&mut self, program: &mut Program) {
......@@ -56,18 +121,63 @@ impl VisitMut for ImportReplacer {
}
}
fn visit_mut_var_declarator(&mut self, decl: &mut VarDeclarator) {
// Detect: const { x, y } = await import('...')
// Collect export names BEFORE visiting children, because visit_mut_expr
// (triggered by visit_mut_children_with) will wrap the import and look up
// the names from the map.
//
// Only extract names when `await` is present — without await, the
// destructuring targets the Promise, not the module namespace.
if let Some(init) = &decl.init {
if let Some(import_span) = find_awaited_import_call_span(init) {
if let Pat::Object(obj_pat) = &decl.name {
if let Some(names) = extract_export_names_from_pat(obj_pat) {
self.import_export_names.insert(import_span.lo, names);
}
}
}
}
decl.visit_mut_children_with(self);
}
fn visit_mut_expr(&mut self, expr: &mut Expr) {
expr.visit_mut_children_with(self);
// before: `import(...)`
// after: `$$trackDynamicImport__(import(...))`
if let Expr::Call(CallExpr {
callee: Callee::Import(_),
..
}) = expr
if let Expr::Call(
call_expr @ CallExpr {
callee: Callee::Import(_),
..
},
) = expr
{
self.has_dynamic_import = true;
// Add /* webpackExports: [...] */ comment if we detected destructuring
if let Some(names) = self.import_export_names.remove(&call_expr.span.lo) {
if let Some(first_arg) = call_expr.args.first() {
let comment_text = if names.is_empty() {
" webpackExports: [] ".to_string()
} else {
let names_json: Vec<String> =
names.iter().map(|n| format!("\"{}\"", n)).collect();
format!(" webpackExports: [{}] ", names_json.join(", "))
};
self.comments.add_leading(
first_arg.span_lo(),
Comment {
span: DUMMY_SP,
kind: CommentKind::Block,
text: comment_text.into(),
},
);
}
}
let replacement_expr = quote!(
"$wrapper_fn($expr)" as Expr,
wrapper_fn = self.wrapper_function_local_ident.clone(),
......
......@@ -954,12 +954,12 @@ fn track_dynamic_imports_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
test_fixture(
syntax(),
&|_tr| {
&|tr| {
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();
(
resolver(unresolved_mark, top_level_mark, false),
track_dynamic_imports(unresolved_mark),
track_dynamic_imports(unresolved_mark, tr.comments.as_ref().clone()),
)
},
&input,
......
import { trackDynamicImport as $$trackDynamicImport__ } from "private-next-rsc-track-dynamic-import";
export default async function Page() {
const { foo } = await /*#__PURE__*/ $$trackDynamicImport__(import('some-module'));
const { foo } = await /*#__PURE__*/ $$trackDynamicImport__(import(/* webpackExports: ["foo"] */ 'some-module'));
return foo();
}
import { trackDynamicImport as $$trackDynamicImport__ } from "private-next-rsc-track-dynamic-import";
export default async function Page() {
const { foo } = await /*#__PURE__*/ $$trackDynamicImport__(import('some-module'));
const { foo } = await /*#__PURE__*/ $$trackDynamicImport__(import(/* webpackExports: ["foo"] */ 'some-module'));
// name conflict
$$trackDynamicImport__1();
return foo();
......
const { ["trackDynamicImport"]: $$trackDynamicImport__ } = require("private-next-rsc-track-dynamic-import");
async function foo() {
const { foo } = await /*#__PURE__*/ $$trackDynamicImport__(import('some-module'));
const { foo } = await /*#__PURE__*/ $$trackDynamicImport__(import(/* webpackExports: ["foo"] */ 'some-module'));
return foo();
}
exports.foo = foo;
// @ts-expect-error destructuring without await is intentional for this test
const { foo } = import('some-module')
export default async function Page() {
const { bar } = await foo
return bar()
}
import { trackDynamicImport as $$trackDynamicImport__ } from "private-next-rsc-track-dynamic-import";
// @ts-expect-error destructuring without await is intentional for this test
const { foo } = /*#__PURE__*/ $$trackDynamicImport__(import('some-module'));
export default async function Page() {
const { bar } = await foo;
return bar();
}
export default async function Page() {
const { constUsed } = await import('../../lib/const-module')
return <div>{constUsed()}</div>
}
export default async function Page() {
const { default: defaultValue } = await import('../../lib/default-module')
return <div>{defaultValue}</div>
}
export default async function Page() {
// eslint-disable-next-line no-empty-pattern
const {} = await import('../../lib/empty-module')
return <div>TREESHAKE_EMPTY_PAGE</div>
}
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default async function Page() {
let { letUsed } = await import('../../lib/let-module')
return <div>{letUsed()}</div>
}
export default async function Page() {
const memberUsed = (await import('../../lib/member-module')).memberUsed
return <div>{memberUsed()}</div>
}
export default async function Page() {
const { multiAUsed } = await import('../../lib/multi-module-a')
const { multiBUsed } = await import('../../lib/multi-module-b')
return (
<div>
{multiAUsed()} {multiBUsed()}
</div>
)
}
export default async function Page() {
const {
nested: { inner },
} = await import('../../lib/nested-module')
return <div>{inner}</div>
}
export default async function Page() {
let mod
mod = await import('../../lib/reassign-module')
return <div>{mod.reassignUsed()}</div>
}
export default async function Page() {
const { renameUsed: myFunc } = await import('../../lib/rename-module')
return <div>{myFunc()}</div>
}
export default async function Page() {
// eslint-disable-next-line no-unused-vars
const { restUsed, ...rest } = await import('../../lib/rest-module')
return <div>{restUsed()}</div>
}
export default async function Page() {
const result = await new Promise((resolve) => {
import('../../lib/then-arrow-module').then(({ thenArrowUsed }) => {
resolve(thenArrowUsed())
})
})
return <div>{result}</div>
}
export default async function Page() {
const result = await new Promise((resolve) => {
import('../../lib/then-function-module').then(function ({ thenFuncUsed }) {
resolve(thenFuncUsed())
})
})
return <div>{result}</div>
}
export default async function Page() {
var { varUsed } = await import('../../lib/var-module')
return <div>{varUsed()}</div>
}
export default async function Page() {
const { commentUsed } = await import(
/* webpackExports: ["commentUsed"] */ '../../lib/comment-module'
)
return <div>{commentUsed()}</div>
}
import { nextTestSetup } from 'e2e-utils'
import fs from 'fs'
import path from 'path'
describe('dynamic-import-tree-shaking', () => {
const { next, skipped, isNextStart, isTurbopack } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
// Recursively read all .js files in a directory
function getAllServerFiles(dir: string): string[] {
const results: string[] = []
try {
const entries = fs.readdirSync(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
results.push(...getAllServerFiles(fullPath))
} else if (entry.name.endsWith('.js')) {
results.push(fullPath)
}
}
} catch {
// directory doesn't exist
}
return results
}
async function getAllServerContent(): Promise<string> {
const serverDir = path.join(next.testDir, '.next/server')
const files = getAllServerFiles(serverDir)
const contents = await Promise.all(
files.map((f) => fs.promises.readFile(f, 'utf8'))
)
return contents.join('\n')
}
// Verify that each page renders correctly (these should always pass in both dev and production)
it('should render const destructure page', async () => {
const $ = await next.render$('/const-destructure')
expect($('div').text()).toContain('TREESHAKE_CONST_USED')
})
it('should render var destructure page', async () => {
const $ = await next.render$('/var-destructure')
expect($('div').text()).toContain('TREESHAKE_VAR_USED')
})
it('should render let destructure page', async () => {
const $ = await next.render$('/let-destructure')
expect($('div').text()).toContain('TREESHAKE_LET_USED')
})
it('should render rename destructure page', async () => {
const $ = await next.render$('/rename-destructure')
expect($('div').text()).toContain('TREESHAKE_RENAME_USED')
})
it('should render nested destructure page', async () => {
const $ = await next.render$('/nested-destructure')
expect($('div').text()).toContain('TREESHAKE_NESTED_USED')
})
it('should render default destructure page', async () => {
const $ = await next.render$('/default-destructure')
expect($('div').text()).toContain('TREESHAKE_DEFAULT_USED')
})
it('should render empty destructure page', async () => {
const $ = await next.render$('/empty-destructure')
expect($('div').text()).toContain('TREESHAKE_EMPTY_PAGE')
})
it('should render member access page', async () => {
const $ = await next.render$('/member-access')
expect($('div').text()).toContain('TREESHAKE_MEMBER_USED')
})
it('should render webpack-exports-comment page', async () => {
const $ = await next.render$('/webpack-exports-comment')
expect($('div').text()).toContain('TREESHAKE_COMMENT_USED')
})
it('should render rest destructure page', async () => {
const $ = await next.render$('/rest-destructure')
expect($('div').text()).toContain('TREESHAKE_REST_USED')
})
it('should render multiple imports page', async () => {
const $ = await next.render$('/multiple-imports')
expect($('div').text()).toContain('TREESHAKE_MULTI_A_USED')
expect($('div').text()).toContain('TREESHAKE_MULTI_B_USED')
})
it('should render reassign page', async () => {
const $ = await next.render$('/reassign')
expect($('div').text()).toContain('TREESHAKE_REASSIGN_USED')
})
it('should render then-arrow-destructure page', async () => {
const $ = await next.render$('/then-arrow-destructure')
expect($('div').text()).toContain('TREESHAKE_THEN_ARROW_USED')
})
it('should render then-function-destructure page', async () => {
const $ = await next.render$('/then-function-destructure')
expect($('div').text()).toContain('TREESHAKE_THEN_FUNC_USED')
})
// Tree shaking assertions: unused exports should NOT be in the server bundle
// Tree shaking is only enabled in production builds, so skip these in dev mode
if (isNextStart) {
it('should tree-shake unused export with const destructured dynamic import', async () => {
const content = await getAllServerContent()
expect(content).toContain('TREESHAKE_CONST_USED')
expect(content).not.toContain('TREESHAKE_CONST_UNUSED')
})
it('should tree-shake unused export with var destructured dynamic import', async () => {
const content = await getAllServerContent()
expect(content).toContain('TREESHAKE_VAR_USED')
expect(content).not.toContain('TREESHAKE_VAR_UNUSED')
})
it('should tree-shake unused export with let destructured dynamic import', async () => {
const content = await getAllServerContent()
expect(content).toContain('TREESHAKE_LET_USED')
expect(content).not.toContain('TREESHAKE_LET_UNUSED')
})
it('should tree-shake unused export with renamed destructured dynamic import', async () => {
const content = await getAllServerContent()
expect(content).toContain('TREESHAKE_RENAME_USED')
expect(content).not.toContain('TREESHAKE_RENAME_UNUSED')
})
it('should tree-shake unused export with nested destructured dynamic import', async () => {
const content = await getAllServerContent()
expect(content).toContain('TREESHAKE_NESTED_USED')
expect(content).not.toContain('TREESHAKE_NESTED_UNUSED')
})
it('should tree-shake unused export with default destructured dynamic import', async () => {
const content = await getAllServerContent()
expect(content).toContain('TREESHAKE_DEFAULT_USED')
expect(content).not.toContain('TREESHAKE_DEFAULT_UNUSED')
})
it('should tree-shake all exports with empty destructured dynamic import', async () => {
const content = await getAllServerContent()
// Side effects should still be included
expect(content).toContain('TREESHAKE_EMPTY_SIDE_EFFECT')
// But no exports should be included
expect(content).not.toContain('TREESHAKE_EMPTY_USED')
expect(content).not.toContain('TREESHAKE_EMPTY_UNUSED')
})
it('should tree-shake unused export with webpackExports comment', async () => {
const content = await getAllServerContent()
expect(content).toContain('TREESHAKE_COMMENT_USED')
expect(content).not.toContain('TREESHAKE_COMMENT_UNUSED')
})
// Member access on dynamic import is only tree-shaken by Turbopack, not webpack
if (isTurbopack) {
it('should tree-shake unused export with member access on dynamic import', async () => {
const content = await getAllServerContent()
expect(content).toContain('TREESHAKE_MEMBER_USED')
expect(content).not.toContain('TREESHAKE_MEMBER_UNUSED')
})
}
it('should NOT tree-shake with rest destructured dynamic import', async () => {
const content = await getAllServerContent()
expect(content).toContain('TREESHAKE_REST_USED')
// rest elements prevent tree-shaking, so unused exports should still be present
expect(content).toContain('TREESHAKE_REST_UNUSED')
})
it('should tree-shake unused exports with multiple dynamic imports in one file', async () => {
const content = await getAllServerContent()
expect(content).toContain('TREESHAKE_MULTI_A_USED')
expect(content).not.toContain('TREESHAKE_MULTI_A_UNUSED')
expect(content).toContain('TREESHAKE_MULTI_B_USED')
expect(content).not.toContain('TREESHAKE_MULTI_B_UNUSED')
})
it('should NOT tree-shake with reassigned dynamic import', async () => {
const content = await getAllServerContent()
expect(content).toContain('TREESHAKE_REASSIGN_USED')
// re-assignment prevents destructuring analysis, so unused exports should remain
expect(content).toContain('TREESHAKE_REASSIGN_UNUSED')
})
// .then() callback destructuring is only tree-shaken by Turbopack, not webpack
if (isTurbopack) {
it('should tree-shake unused export with .then() arrow destructured dynamic import', async () => {
const content = await getAllServerContent()
expect(content).toContain('TREESHAKE_THEN_ARROW_USED')
expect(content).not.toContain('TREESHAKE_THEN_ARROW_UNUSED')
})
it('should tree-shake unused export with .then() function destructured dynamic import', async () => {
const content = await getAllServerContent()
expect(content).toContain('TREESHAKE_THEN_FUNC_USED')
expect(content).not.toContain('TREESHAKE_THEN_FUNC_UNUSED')
})
}
}
})
export function commentUsed() {
return 'TREESHAKE_COMMENT_USED'
}
export function commentUnused() {
return 'TREESHAKE_COMMENT_UNUSED'
}
export function constUsed() {
return 'TREESHAKE_CONST_USED'
}
export function constUnused() {
return 'TREESHAKE_CONST_UNUSED'
}
export default 'TREESHAKE_DEFAULT_USED'
export function defaultUnused() {
return 'TREESHAKE_DEFAULT_UNUSED'
}
// This side effect should always be included
console.log('TREESHAKE_EMPTY_SIDE_EFFECT')
export function emptyUsed() {
return 'TREESHAKE_EMPTY_USED'
}
export function emptyUnused() {
return 'TREESHAKE_EMPTY_UNUSED'
}
export function letUsed() {
return 'TREESHAKE_LET_USED'
}
export function letUnused() {
return 'TREESHAKE_LET_UNUSED'
}
export function memberUsed() {
return 'TREESHAKE_MEMBER_USED'
}
export function memberUnused() {
return 'TREESHAKE_MEMBER_UNUSED'
}
export function multiAUsed() {
return 'TREESHAKE_MULTI_A_USED'
}
export function multiAUnused() {
return 'TREESHAKE_MULTI_A_UNUSED'
}
export function multiBUsed() {
return 'TREESHAKE_MULTI_B_USED'
}
export function multiBUnused() {
return 'TREESHAKE_MULTI_B_UNUSED'
}
export const nested = {
inner: 'TREESHAKE_NESTED_USED',
}
export function nestedUnused() {
return 'TREESHAKE_NESTED_UNUSED'
}
export function reassignUsed() {
return 'TREESHAKE_REASSIGN_USED'
}
export function reassignUnused() {
return 'TREESHAKE_REASSIGN_UNUSED'
}
export function renameUsed() {
return 'TREESHAKE_RENAME_USED'
}
export function renameUnused() {
return 'TREESHAKE_RENAME_UNUSED'
}
export function restUsed() {
return 'TREESHAKE_REST_USED'
}
export function restUnused() {
return 'TREESHAKE_REST_UNUSED'
}
export function thenArrowUsed() {
return 'TREESHAKE_THEN_ARROW_USED'
}
export function thenArrowUnused() {
return 'TREESHAKE_THEN_ARROW_UNUSED'
}
export function thenFuncUsed() {
return 'TREESHAKE_THEN_FUNC_USED'
}
export function thenFuncUnused() {
return 'TREESHAKE_THEN_FUNC_UNUSED'
}
export function varUsed() {
return 'TREESHAKE_VAR_USED'
}
export function varUnused() {
return 'TREESHAKE_VAR_UNUSED'
}
......@@ -332,10 +332,21 @@ impl ModuleExportUsageInfo {
*self = Self::Exports(AutoSet::from_iter([name.clone()]));
true
}
(Self::Evaluation, ExportUsage::PartialNamespaceObject(names)) => {
*self = Self::Exports(AutoSet::from_iter(names.iter().cloned()));
true
}
(Self::Exports(l), ExportUsage::Named(r)) => {
// Merge exports
l.insert(r.clone())
}
(Self::Exports(l), ExportUsage::PartialNamespaceObject(names)) => {
let mut changed = false;
for name in names {
changed |= l.insert(name.clone());
}
changed
}
(_, ExportUsage::Evaluation) => false,
}
}
......
......@@ -526,9 +526,12 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc<
// necessarily needed for browser),
exposed_modules_imported.insert(module);
}
if parent_info
.is_some_and(|(_, r)| matches!(r.binding_usage.export, ExportUsage::All))
{
if parent_info.is_some_and(|(_, r)| {
matches!(
r.binding_usage.export,
ExportUsage::All | ExportUsage::PartialNamespaceObject(_)
)
}) {
// This module needs to be exposed:
// - namespace import from another group
exposed_modules_namespace.insert(module);
......
......@@ -161,6 +161,8 @@ pub enum ImportUsage {
#[derive(Debug, Clone, Default, Hash, Serialize, Deserialize)]
pub enum ExportUsage {
Named(RcStr),
/// Multiple named exports are used via a partial namespace object.
PartialNamespaceObject(SmallVec<[RcStr; 1]>),
/// This means the whole content of the module is used.
#[default]
All,
......@@ -172,6 +174,16 @@ impl Display for ExportUsage {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ExportUsage::Named(name) => write!(f, "export {name}"),
ExportUsage::PartialNamespaceObject(names) => {
write!(f, "exports ")?;
for (i, name) in names.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{name}")?;
}
Ok(())
}
ExportUsage::All => write!(f, "all"),
ExportUsage::Evaluation => write!(f, "evaluation"),
}
......
......@@ -6,6 +6,7 @@ use std::{
use anyhow::{Ok, Result};
use rustc_hash::{FxHashMap, FxHashSet};
use smallvec::SmallVec;
use swc_core::{
atoms::Atom,
base::try_with_handler,
......@@ -22,7 +23,7 @@ use swc_core::{
};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::ResolvedVc;
use turbopack_core::source::Source;
use turbopack_core::{resolve::ExportUsage, source::Source};
use super::{
ConstantNumber, ConstantValue, ImportMap, JsValue, ObjectPart, WellKnownFunctionKind,
......@@ -203,6 +204,23 @@ pub enum Effect {
ast_path: Vec<AstParentKind>,
span: Span,
},
/// A dynamic import() call, potentially with export usage extracted from
/// usage patterns. Export usage is detected from these patterns:
///
/// - `const { a, b } = await import('./lib')` (destructured await)
/// - `(await import('./lib')).a` (member access on await)
/// - `import('./lib').then(({ a, b }) => {})` (arrow .then() callback)
/// - `import('./lib').then(function({ a, b }) {})` (function .then() callback)
/// - `import(/* webpackExports: ["a"] */ './lib')` (magic comment)
/// - `import(/* turbopackExports: ["a"] */ './lib')` (magic comment)
DynamicImport {
args: Vec<EffectArg>,
ast_path: Vec<AstParentKind>,
span: Span,
in_try: bool,
/// The export usage extracted from the usage pattern.
export_usage: ExportUsage,
},
/// Unreachable code, e.g. after a `return` statement.
Unreachable { start_ast_path: Vec<AstParentKind> },
}
......@@ -236,6 +254,11 @@ impl Effect {
obj.normalize();
prop.normalize();
}
Effect::DynamicImport { args, .. } => {
for arg in args.iter_mut() {
arg.normalize();
}
}
Effect::ImportedBinding { .. } => {}
Effect::TypeOf { arg, .. } => {
arg.normalize();
......@@ -1329,6 +1352,137 @@ pub fn as_parent_path(ast_path: &AstNodePath<AstParentNodeRef<'_>>) -> Vec<AstPa
ast_path.iter().map(|n| n.kind()).collect()
}
/// Extracts export names from usage patterns on a dynamic import.
///
/// Supports two patterns:
/// 1. Destructuring: `const { cat, dog } = await import('./lib')` → `PartialNamespaceObject(["cat",
/// "dog"])`
/// 2. Member access: `(await import('./lib')).cat` → `PartialNamespaceObject(["cat"])`
///
/// For `const {} = await import('./lib')`, returns `Evaluation`.
/// For `const mod = await import('./lib')` or non-recognized patterns, returns `All`.
/// For patterns with rest elements or computed keys, returns `All` (conservative).
fn extract_dynamic_import_export_usage(
ast_path: &AstNodePath<AstParentNodeRef<'_>>,
) -> ExportUsage {
// Walk up the AST path from the import() call to find usage patterns that
// reveal which exports are needed. Supported patterns:
//
// 1. Destructured await: const { a, b } = await import('./lib')
// 2. Member access on await: (await import('./lib')).a
// 3. Arrow .then() callback: import('./lib').then(({ a, b }) => {})
// 4. Function .then() callback: import('./lib').then(function({ a, b }) {})
//
// Only allow Expr wrappers, AwaitExpr, ParenExpr, and Callee as intermediate
// nodes to ensure the import result flows directly into the usage site.
let mut seen_await = false;
let mut seen_then = false;
let names = 'outer: {
for node_ref in ast_path.iter().rev() {
match node_ref {
// Only extract names when `await` is present — without await, the
// destructuring targets the Promise, not the module namespace.
AstParentNodeRef::VarDeclarator(decl, VarDeclaratorField::Init) if seen_await => {
break 'outer extract_names_from_object_pat(&decl.name);
}
// Member access: (await import('./lib')).someExport
// Only valid after AwaitExpr — without await, it's a Promise method
AstParentNodeRef::MemberExpr(member, MemberExprField::Obj) if seen_await => {
break 'outer extract_name_from_member_prop(&member.prop);
}
// Promise .then() pattern: import('./lib').then(({ name }) => {})
// Without await, check if this is a .then() call and extract from callback
AstParentNodeRef::MemberExpr(member, MemberExprField::Obj) => {
if matches!(&member.prop, MemberProp::Ident(ident) if &*ident.sym == "then") {
seen_then = true;
continue;
}
break 'outer None;
}
// After seeing .then MemberExpr, the next CallExpr is the .then() call
// — extract destructured parameter names from the first callback argument
AstParentNodeRef::CallExpr(call, CallExprField::Callee) if seen_then => {
break 'outer extract_names_from_then_callback(call);
}
AstParentNodeRef::AwaitExpr(_, AwaitExprField::Arg) => {
seen_await = true;
continue;
}
// Allowed intermediate nodes
AstParentNodeRef::Expr(..)
| AstParentNodeRef::ParenExpr(_, ParenExprField::Expr)
| AstParentNodeRef::Callee(_, CalleeField::Expr) => continue,
// Any other node means the import is nested in something else
_ => break 'outer None,
}
}
None
};
match names {
Some(names) if names.is_empty() => ExportUsage::Evaluation,
Some(names) => ExportUsage::PartialNamespaceObject(names),
None => ExportUsage::All,
}
}
/// Extract export names from the first argument of a `.then()` callback.
/// Supports both arrow functions and function expressions with destructured
/// first parameters.
fn extract_names_from_then_callback(call: &CallExpr) -> Option<SmallVec<[RcStr; 1]>> {
let first_arg = call.args.first()?;
if first_arg.spread.is_some() {
return None;
}
match &*first_arg.expr {
// Arrow function: import('./lib').then(({ name }) => {})
Expr::Arrow(arrow) => {
let first_param = arrow.params.first()?;
extract_names_from_object_pat(first_param)
}
// Function expression: import('./lib').then(function({ name }) {})
Expr::Fn(fn_expr) => {
let first_param = fn_expr.function.params.first()?;
extract_names_from_object_pat(&first_param.pat)
}
_ => None,
}
}
fn extract_name_from_member_prop(prop: &MemberProp) -> Option<SmallVec<[RcStr; 1]>> {
match prop {
MemberProp::Ident(ident) => Some(SmallVec::from_buf([ident.sym.as_str().into()])),
MemberProp::Computed(ComputedPropName {
expr: box Expr::Lit(Lit::Str(s)),
..
}) => s.value.as_str().map(|v| SmallVec::from_buf([v.into()])),
_ => None,
}
}
fn extract_names_from_object_pat(pat: &Pat) -> Option<SmallVec<[RcStr; 1]>> {
let Pat::Object(obj_pat) = pat else {
return None;
};
let mut names = SmallVec::new();
for prop in &obj_pat.props {
match prop {
ObjectPatProp::KeyValue(kv) => match &kv.key {
PropName::Ident(ident) => names.push(ident.sym.as_str().into()),
PropName::Str(s) => match s.value.as_str() {
Some(str_val) => names.push(str_val.into()),
None => return None, // non-UTF-8 string key
},
_ => return None, // computed key, can't determine statically
},
ObjectPatProp::Assign(assign) => {
names.push(assign.key.sym.as_str().into());
}
ObjectPatProp::Rest(_) => return None, // rest pattern means all exports needed
}
}
Some(names)
}
pub fn as_parent_path_with(
ast_path: &AstNodePath<AstParentNodeRef<'_>>,
additional: AstParentKind,
......@@ -1680,13 +1834,24 @@ impl Analyzer<'_> {
match callee {
Callee::Import(_) => {
self.add_effect(Effect::Call {
func: Box::new(JsValue::FreeVar(atom!("import"))),
// Prefer webpackExports/turbopackExports comment (authoritative when present)
let attrs = self.eval_context.imports.get_attributes(span);
let export_usage = if let Some(names) = &attrs.export_names {
if names.is_empty() {
ExportUsage::Evaluation
} else {
ExportUsage::PartialNamespaceObject(names.clone())
}
} else {
// Fall back to AST path walking (works when import is not wrapped)
extract_dynamic_import_export_usage(ast_path)
};
self.add_effect(Effect::DynamicImport {
args,
ast_path: as_parent_path(ast_path),
span,
in_try: self.is_in_try(),
new,
export_usage,
});
}
Callee::Expr(box expr) => {
......
......@@ -2,6 +2,7 @@ use std::{borrow::Cow, collections::BTreeMap, fmt::Display};
use once_cell::sync::Lazy;
use rustc_hash::{FxHashMap, FxHashSet};
use smallvec::SmallVec;
use swc_core::{
atoms::Wtf8Atom,
common::{BytePos, Span, Spanned, SyntaxContext, comments::Comments, source_map::SmallPos},
......@@ -299,6 +300,20 @@ pub struct ImportAttributes {
/// const a = import(/* turbopackOptional: true */ "a");
/// ```
pub optional: bool,
/// Which exports are used from a dynamic import. When set, enables tree-shaking for the
/// dynamically imported module by only including the specified exports.
///
/// This is set by using either a `webpackExports` or `turbopackExports` comment.
/// `None` means no directive was found (all exports assumed used).
/// `Some([])` means empty list (only side effects).
/// `Some([name, ...])` means specific named exports are used.
///
/// Example:
/// ```js
/// const { a } = await import(/* webpackExports: ["a"] */ "module");
/// const { b } = await import(/* turbopackExports: "b" */ "module");
/// ```
pub export_names: Option<SmallVec<[RcStr; 1]>>,
}
impl ImportAttributes {
......@@ -306,6 +321,7 @@ impl ImportAttributes {
ImportAttributes {
ignore: false,
optional: false,
export_names: None,
}
}
......@@ -883,31 +899,69 @@ fn parse_directives(
let mut ignore = None;
let mut optional = None;
let mut export_names = None;
// Process all comments, last one wins for each directive type
for comment in leading_comments.iter() {
if let Some((directive, val)) = comment.text.trim().split_once(':') {
match (directive.trim(), val.trim()) {
("webpackIgnore" | "turbopackIgnore", "true") => ignore = Some(true),
("webpackIgnore" | "turbopackIgnore", "false") => ignore = Some(false),
("turbopackOptional", "true") => optional = Some(true),
("turbopackOptional", "false") => optional = Some(false),
let val = val.trim();
match directive.trim() {
"webpackIgnore" | "turbopackIgnore" => match val {
"true" => ignore = Some(true),
"false" => ignore = Some(false),
_ => {}
},
"turbopackOptional" => match val {
"true" => optional = Some(true),
"false" => optional = Some(false),
_ => {}
},
"webpackExports" | "turbopackExports" => {
export_names = Some(parse_export_names(val));
}
_ => {} // ignore anything else
}
}
}
// Return Some only if at least one directive was found
if ignore.is_some() || optional.is_some() {
if ignore.is_some() || optional.is_some() || export_names.is_some() {
Some(ImportAttributes {
ignore: ignore.unwrap_or(false),
optional: optional.unwrap_or(false),
export_names,
})
} else {
None
}
}
/// Parse export names from a `webpackExports` or `turbopackExports` comment value.
///
/// Supports two formats:
/// - Single string: `"name"` → `["name"]`
/// - JSON array: `["name1", "name2"]` → `["name1", "name2"]`
fn parse_export_names(val: &str) -> SmallVec<[RcStr; 1]> {
let val = val.trim();
// Try parsing as JSON array of strings
if let Ok(names) = serde_json::from_str::<Vec<String>>(val) {
return names.into_iter().map(|s| s.into()).collect();
}
// Try parsing as a single JSON string
if let Ok(name) = serde_json::from_str::<String>(val) {
return SmallVec::from_buf([name.into()]);
}
// Bare identifier (no quotes)
if !val.is_empty() {
return SmallVec::from_buf([val.into()]);
}
SmallVec::new()
}
fn parse_with(with: Option<&ObjectLit>) -> Option<ImportedSymbol> {
find_turbopack_part_id_in_asserts(with?).map(|v| match v {
PartId::Internal(index, true) => ImportedSymbol::PartEvaluation(index),
......
......@@ -4052,6 +4052,18 @@ mod tests {
));
obj_steps + prop_steps
}
Effect::DynamicImport { args, .. } => {
let new_args =
handle_args(args, &mut queue, &var_graph, &var_cache, i).await;
resolved.push((
format!("{parent} -> {i} dynamic import"),
JsValue::call(
Box::new(JsValue::FreeVar("import".into())),
new_args,
),
));
0
}
Effect::Unreachable { .. } => {
resolved.push((
format!("{parent} -> {i} unreachable"),
......
......@@ -15,7 +15,7 @@ use turbopack_core::{
reference::ModuleReference,
reference_type::EcmaScriptModulesReferenceSubType,
resolve::{
ModuleResolveResult, ResolveErrorMode,
BindingUsage, ExportUsage, ModuleResolveResult, ResolveErrorMode,
origin::{ResolveOrigin, ResolveOriginExt},
parse::Request,
},
......@@ -42,6 +42,10 @@ pub struct EsmAsyncAssetReference {
pub issue_source: IssueSource,
pub error_mode: ResolveErrorMode,
pub import_externals: bool,
/// The export usage extracted from the dynamic import usage pattern.
/// Detected from destructured await, member access on await, .then()
/// callback destructuring, or webpackExports/turbopackExports comments.
pub export_usage: ExportUsage,
}
impl EsmAsyncAssetReference {
......@@ -62,6 +66,7 @@ impl EsmAsyncAssetReference {
annotations: ImportAnnotations,
error_mode: ResolveErrorMode,
import_externals: bool,
export_usage: ExportUsage,
) -> Self {
EsmAsyncAssetReference {
origin,
......@@ -70,6 +75,7 @@ impl EsmAsyncAssetReference {
annotations,
error_mode,
import_externals,
export_usage,
}
}
}
......@@ -92,6 +98,15 @@ impl ModuleReference for EsmAsyncAssetReference {
fn chunking_type(&self) -> Vc<ChunkingTypeOption> {
Vc::cell(Some(ChunkingType::Async))
}
#[turbo_tasks::function]
fn binding_usage(&self) -> Vc<BindingUsage> {
BindingUsage {
import: Default::default(),
export: self.export_usage.clone(),
}
.cell()
}
}
impl IntoCodeGenReference for EsmAsyncAssetReference {
......
......@@ -78,7 +78,8 @@ use turbopack_core::{
reference::{ModuleReference, ModuleReferences},
reference_type::{CommonJsReferenceSubType, ReferenceType},
resolve::{
FindContextFileResult, ImportUsage, ModulePart, ResolveErrorMode, find_context_file,
ExportUsage, FindContextFileResult, ImportUsage, ModulePart, ResolveErrorMode,
find_context_file,
origin::{PlainResolveOrigin, ResolveOrigin},
parse::Request,
pattern::Pattern,
......@@ -1324,6 +1325,32 @@ async fn analyze_ecmascript_module_internal(
)
.await?;
}
Effect::DynamicImport {
args,
ast_path,
span,
in_try,
export_usage,
} => {
if let Some(ignored) = &ignore_effect_span
&& *ignored == span
{
continue;
}
handle_dynamic_import(
&ast_path,
span,
args,
&analysis_state,
&add_effects,
&mut analysis,
in_try,
eval_context.imports.get_attributes(span),
export_usage,
)
.await?;
}
Effect::MemberCall {
obj,
prop,
......@@ -1812,6 +1839,149 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
Ok(())
}
async fn handle_dynamic_import<G: Fn(Vec<Effect>) + Send + Sync>(
ast_path: &[AstParentKind],
span: Span,
args: Vec<EffectArg>,
state: &AnalysisState<'_>,
add_effects: &G,
analysis: &mut AnalyzeEcmascriptModuleResultBuilder,
in_try: bool,
attributes: &ImportAttributes,
export_usage: ExportUsage,
) -> Result<()> {
// If the import has a webpackIgnore/turbopackIgnore comment, skip processing
// so the import expression is preserved as-is in the output.
if attributes.ignore {
return Ok(());
}
let &AnalysisState {
handler,
origin,
source,
ignore_dynamic_requests,
..
} = state;
let error_mode = if attributes.optional {
ResolveErrorMode::Ignore
} else if in_try {
ResolveErrorMode::Warn
} else {
ResolveErrorMode::Error
};
// Process all effects (closures) from args
let unlinked_args: Vec<JsValue> = args
.into_iter()
.map(|effect_arg| match effect_arg {
EffectArg::Value(value) => value,
EffectArg::Closure(value, block) => {
add_effects(block.effects);
value
}
EffectArg::Spread => JsValue::unknown_empty(true, "spread is not supported yet"),
})
.collect();
let linked_args = unlinked_args
.iter()
.cloned()
.map(|arg| state.link_value(arg, ImportAttributes::empty_ref()))
.try_join()
.await?;
handle_dynamic_import_with_linked_args(
ast_path,
span,
&linked_args,
handler,
origin,
source,
ignore_dynamic_requests,
analysis,
error_mode,
state.import_externals,
export_usage,
)
.await
}
async fn handle_dynamic_import_with_linked_args(
ast_path: &[AstParentKind],
span: Span,
linked_args: &[JsValue],
handler: &Handler,
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
source: ResolvedVc<Box<dyn Source>>,
ignore_dynamic_requests: bool,
analysis: &mut AnalyzeEcmascriptModuleResultBuilder,
error_mode: ResolveErrorMode,
import_externals: bool,
export_usage: ExportUsage,
) -> Result<()> {
if linked_args.len() == 1 || linked_args.len() == 2 {
let pat = js_value_to_pattern(&linked_args[0]);
let options = linked_args.get(1);
let import_annotations = options
.and_then(|options| {
if let JsValue::Object { parts, .. } = options {
parts.iter().find_map(|part| {
if let ObjectPart::KeyValue(
JsValue::Constant(super::analyzer::ConstantValue::Str(key)),
value,
) = part
&& key.as_str() == "with"
{
return Some(value);
}
None
})
} else {
None
}
})
.and_then(ImportAnnotations::parse_dynamic)
.unwrap_or_default();
if !pat.has_constant_parts() {
let (args, hints) = JsValue::explain_args(linked_args, 10, 2);
handler.span_warn_with_code(
span,
&format!("import({args}) is very dynamic{hints}",),
DiagnosticId::Lint(
errors::failed_to_analyze::ecmascript::DYNAMIC_IMPORT.to_string(),
),
);
if ignore_dynamic_requests {
analysis.add_code_gen(DynamicExpression::new_promise(ast_path.to_vec().into()));
return Ok(());
}
}
analysis.add_reference_code_gen(
EsmAsyncAssetReference::new(
origin,
Request::parse(pat).to_resolved().await?,
issue_source(source, span),
import_annotations,
error_mode,
import_externals,
export_usage,
),
ast_path.to_vec().into(),
);
return Ok(());
}
let (args, hints) = JsValue::explain_args(linked_args, 10, 2);
handler.span_warn_with_code(
span,
&format!("import({args}) is not statically analyze-able{hints}",),
DiagnosticId::Error(errors::failed_to_analyze::ecmascript::DYNAMIC_IMPORT.to_string()),
);
Ok(())
}
async fn handle_well_known_function_call<'a, F, Fut>(
func: WellKnownFunctionKind,
new: bool,
......@@ -2024,65 +2194,25 @@ where
match func {
WellKnownFunctionKind::Import => {
let args = linked_args().await?;
if args.len() == 1 || args.len() == 2 {
let pat = js_value_to_pattern(&args[0]);
let options = args.get(1);
let import_annotations = options
.and_then(|options| {
if let JsValue::Object { parts, .. } = options {
parts.iter().find_map(|part| {
if let ObjectPart::KeyValue(
JsValue::Constant(super::analyzer::ConstantValue::Str(key)),
value,
) = part
&& key.as_str() == "with"
{
return Some(value);
}
None
})
} else {
None
}
})
.and_then(ImportAnnotations::parse_dynamic)
.unwrap_or_default();
if !pat.has_constant_parts() {
let (args, hints) = explain_args(args);
handler.span_warn_with_code(
span,
&format!("import({args}) is very dynamic{hints}",),
DiagnosticId::Lint(
errors::failed_to_analyze::ecmascript::DYNAMIC_IMPORT.to_string(),
),
);
if ignore_dynamic_requests {
analysis
.add_code_gen(DynamicExpression::new_promise(ast_path.to_vec().into()));
return Ok(());
}
}
analysis.add_reference_code_gen(
EsmAsyncAssetReference::new(
origin,
Request::parse(pat).to_resolved().await?,
issue_source(source, span),
import_annotations,
error_mode,
state.import_externals,
),
ast_path.to_vec().into(),
);
return Ok(());
}
let (args, hints) = explain_args(args);
handler.span_warn_with_code(
let export_usage = match &attributes.export_names {
Some(names) if names.is_empty() => ExportUsage::Evaluation,
Some(names) => ExportUsage::PartialNamespaceObject(names.clone()),
None => ExportUsage::All,
};
handle_dynamic_import_with_linked_args(
ast_path,
span,
&format!("import({args}) is not statically analyze-able{hints}",),
DiagnosticId::Error(
errors::failed_to_analyze::ecmascript::DYNAMIC_IMPORT.to_string(),
),
args,
handler,
origin,
source,
ignore_dynamic_requests,
analysis,
error_mode,
state.import_externals,
export_usage,
)
.await?;
}
WellKnownFunctionKind::Require => {
let args = linked_args().await?;
......
......@@ -179,7 +179,9 @@ impl EcmascriptModulePartReference {
chunking_context,
match &*export_usage {
ExportUsage::Named(export) => Some(export.clone()),
ExportUsage::All | ExportUsage::Evaluation => None,
ExportUsage::PartialNamespaceObject(_)
| ExportUsage::All
| ExportUsage::Evaluation => None,
},
scope_hoisting_context,
)
......
......@@ -149,10 +149,7 @@
],
span: 18..34,
},
Call {
func: FreeVar(
"import",
),
DynamicImport {
args: [
Value(
Constant(
......@@ -196,7 +193,7 @@
],
span: 11..35,
in_try: false,
new: false,
export_usage: All,
},
Member {
obj: Member(
......@@ -596,10 +593,7 @@
],
span: 57..196,
},
Call {
func: FreeVar(
"import",
),
DynamicImport {
args: [
Value(
Tenary(
......@@ -687,7 +681,7 @@
],
span: 47..198,
in_try: false,
new: false,
export_usage: All,
},
Conditional {
condition: Constant(
......@@ -696,10 +690,7 @@
kind: IfElse {
then: EffectsBlock {
effects: [
Call {
func: FreeVar(
"import",
),
DynamicImport {
args: [
Value(
Constant(
......@@ -755,7 +746,7 @@
],
span: 226..237,
in_try: false,
new: false,
export_usage: All,
},
],
range: Exact(
......@@ -782,10 +773,7 @@
},
else: EffectsBlock {
effects: [
Call {
func: FreeVar(
"import",
),
DynamicImport {
args: [
Value(
Constant(
......@@ -841,7 +829,7 @@
],
span: 254..265,
in_try: false,
new: false,
export_usage: All,
},
],
range: Exact(
......@@ -1224,10 +1212,7 @@
],
span: 399..434,
},
Call {
func: FreeVar(
"import",
),
DynamicImport {
args: [
Value(
Constant(
......@@ -1280,7 +1265,7 @@
],
span: 438..449,
in_try: false,
new: false,
export_usage: All,
},
ImportedBinding {
esm_reference_index: 4,
......
0 -> 1 conditional = true
0 -> 2 call = import*0*("a")
- *0* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
0 -> 2 dynamic import = FreeVar(import)("a")
0 -> 5 free var = FreeVar(process)
0 -> 6 conditional = (process.env*0*["NEXT_RUNTIME"] === "edge")
- *0* process.env: The Node.js process.env property: https://nodejs.org/api/process.html#processenv
0 -> 7 call = import*0*(
(???*1* ? "next/dist/compiled/@vercel/og/index.edge.js" : "next/dist/compiled/@vercel/og/index.node.js")
0 -> 7 dynamic import = FreeVar(import)(
(???*0* ? "next/dist/compiled/@vercel/og/index.edge.js" : "next/dist/compiled/@vercel/og/index.node.js")
)
- *0* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
- *1* (process.env*2*["NEXT_RUNTIME"] === "edge")
- *0* (process.env*1*["NEXT_RUNTIME"] === "edge")
⚠️ nested operation
- *2* process.env: The Node.js process.env property: https://nodejs.org/api/process.html#processenv
- *1* process.env: The Node.js process.env property: https://nodejs.org/api/process.html#processenv
0 -> 8 conditional = true
8 -> 9 call = import*0*("a")
- *0* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
8 -> 9 dynamic import = FreeVar(import)("a")
8 -> 10 call = import*0*("b")
- *0* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
8 -> 10 dynamic import = FreeVar(import)("b")
0 -> 11 conditional = true
......@@ -32,5 +28,4 @@
- *0* unreachable
⚠️ This value might have side effects
0 -> 16 call = import*0*("c")
- *0* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
0 -> 16 dynamic import = FreeVar(import)("c")
......@@ -1163,10 +1163,7 @@
],
span: 514..519,
},
Call {
func: FreeVar(
"import",
),
DynamicImport {
args: [
Value(
Constant(
......@@ -1216,6 +1213,10 @@
],
span: 556..570,
in_try: false,
new: false,
export_usage: PartialNamespaceObject(
[
"join",
],
),
},
]
......@@ -33,5 +33,4 @@
0 -> 17 call = require*0*("path")
- *0* require: The require method from CommonJS
0 -> 22 call = import*0*("path")
- *0* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
0 -> 22 dynamic import = FreeVar(import)("path")
[
Call {
func: FreeVar(
"import",
),
DynamicImport {
args: [
Value(
Constant(
......@@ -52,7 +49,7 @@
],
span: 19..58,
in_try: false,
new: false,
export_usage: All,
},
FreeVar {
var: "require",
......@@ -146,10 +143,7 @@
in_try: false,
new: false,
},
Call {
func: FreeVar(
"import",
),
DynamicImport {
args: [
Value(
Constant(
......@@ -199,7 +193,7 @@
],
span: 133..174,
in_try: false,
new: false,
export_usage: All,
},
FreeVar {
var: "require",
......
0 -> 1 call = ???*0*("w_i")
- *0* import*1*
⚠️ ignored import
⚠️ This value might have side effects
- *1* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
0 -> 1 dynamic import = FreeVar(import)("w_i")
0 -> 2 free var = FreeVar(require)
0 -> 3 call = require*0*("w_i_f")
- *0* require: The require method from CommonJS
0 -> 4 call = ???*0*("t_i")
- *0* import*1*
⚠️ ignored import
⚠️ This value might have side effects
- *1* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
0 -> 4 dynamic import = FreeVar(import)("t_i")
0 -> 5 free var = FreeVar(require)
......
it('should mark all exports as used with non-destructured dynamic import', async () => {
const lib = await import('./modules/all')
expect(lib.cat).toBe('cat')
expect(lib.exportsInfo.cat.used).toBe(true)
expect(lib.exportsInfo.dog.used).toBe(true)
})
it('should tree-shake unused exports with const destructured dynamic import', async () => {
const { cat, exportsInfo } = await import('./modules/const')
expect(cat).toBe('cat')
expect(exportsInfo.cat.used).toBe(true)
expect(exportsInfo.dog.used).toBe(false)
})
it('should tree-shake unused exports with let destructured dynamic import', async () => {
let { cat, exportsInfo } = await import('./modules/let')
expect(cat).toBe('cat')
expect(exportsInfo.cat.used).toBe(true)
expect(exportsInfo.dog.used).toBe(false)
})
it('should tree-shake unused exports with var destructured dynamic import', async () => {
var { cat, exportsInfo } = await import('./modules/var')
expect(cat).toBe('cat')
expect(exportsInfo.cat.used).toBe(true)
expect(exportsInfo.dog.used).toBe(false)
})
it('should tree-shake all exports with empty destructured dynamic import', async () => {
const { exportsInfo } = await import('./modules/empty')
expect(exportsInfo.cat.used).toBe(false)
expect(exportsInfo.dog.used).toBe(false)
})
it('should tree-shake unused exports with renamed destructured dynamic import', async () => {
const { cat: myCat, exportsInfo } = await import('./modules/rename')
expect(myCat).toBe('cat')
expect(exportsInfo.cat.used).toBe(true)
expect(exportsInfo.dog.used).toBe(false)
})
it('should tree-shake unused exports with nested destructured dynamic import', async () => {
const {
dog: { name },
exportsInfo,
} = await import('./modules/nested')
expect(name).toBe('dog')
expect(exportsInfo.dog.used).toBe(true)
expect(exportsInfo.cat.used).toBe(false)
})
it('should tree-shake unused exports with member access on dynamic import', async () => {
const cat = (await import('./modules/member')).cat
const { exportsInfo } = await import('./modules/member')
expect(cat).toBe('cat')
expect(exportsInfo.cat.used).toBe(true)
expect(exportsInfo.dog.used).toBe(false)
})
it('should tree-shake unused exports with .then() arrow destructured dynamic import', async () => {
const result = await new Promise((resolve) => {
import('./modules/then-arrow').then(({ cat, exportsInfo }) => {
resolve({ cat, exportsInfo })
})
})
expect(result.cat).toBe('cat')
expect(result.exportsInfo.cat.used).toBe(true)
expect(result.exportsInfo.dog.used).toBe(false)
})
it('should tree-shake unused exports with .then() function destructured dynamic import', async () => {
const result = await new Promise((resolve) => {
import('./modules/then-fn').then(function ({
cat,
default: def,
exportsInfo,
}) {
resolve({ cat, def, exportsInfo })
})
})
expect(result.cat).toBe('cat')
expect(result.def).toBe('the default value')
expect(result.exportsInfo.cat.used).toBe(true)
expect(result.exportsInfo.default.used).toBe(true)
expect(result.exportsInfo.dog.used).toBe(false)
})
it('should tree-shake unused exports with default destructured dynamic import', async () => {
const { default: defaultValue, exportsInfo } = await import(
'./modules/default'
)
expect(defaultValue).toBe('the default value')
expect(exportsInfo.default.used).toBe(true)
expect(exportsInfo.cat.used).toBe(false)
expect(exportsInfo.dog.used).toBe(false)
})
it('should tree-shake unused exports with turbopackExports comment', async () => {
const { cat, exportsInfo } = await import(
/* turbopackExports: ["cat", "exportsInfo"] */ './modules/turbopack'
)
expect(cat).toBe('cat')
expect(exportsInfo.cat.used).toBe(true)
expect(exportsInfo.dog.used).toBe(false)
})
it('should tree-shake unused exports with webpackExports comment', async () => {
const { cat, exportsInfo } = await import(
/* webpackExports: ["cat", "exportsInfo"] */ './modules/webpack'
)
expect(cat).toBe('cat')
expect(exportsInfo.cat.used).toBe(true)
expect(exportsInfo.dog.used).toBe(false)
})
export const cat = 'cat'
export const dog = 'dog'
export const exportsInfo = __webpack_exports_info__
export const cat = 'cat'
export const dog = 'dog'
export const exportsInfo = __webpack_exports_info__
export const cat = 'cat'
export const dog = 'dog'
export default 'the default value'
export const exportsInfo = __webpack_exports_info__
export const cat = 'cat'
export const dog = 'dog'
export const exportsInfo = __webpack_exports_info__
export const cat = 'cat'
export const dog = 'dog'
export const exportsInfo = __webpack_exports_info__
export const cat = 'cat'
export const dog = 'dog'
export const exportsInfo = __webpack_exports_info__
export const cat = 'cat'
export const dog = { name: 'dog' }
export const exportsInfo = __webpack_exports_info__
export const cat = 'cat'
export const dog = 'dog'
export const exportsInfo = __webpack_exports_info__
export const cat = 'cat'
export const dog = 'dog'
export const exportsInfo = __webpack_exports_info__
export const cat = 'cat'
export const dog = 'dog'
export default 'the default value'
export const exportsInfo = __webpack_exports_info__
export const cat = 'cat'
export const dog = 'dog'
export const exportsInfo = __webpack_exports_info__
export const cat = 'cat'
export const dog = 'dog'
export const exportsInfo = __webpack_exports_info__
export const cat = 'cat'
export const dog = 'dog'
export const exportsInfo = __webpack_exports_info__
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