Unverified Commit 33a09d53 authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Tree-shake `module.exports = {...}` (CJS) (#95996)

This PR builds on https://github.com/vercel/next.js/pull/95716 by adding
support tree-shaking exports exported using the `module.exports = {...}`
syntax
parent af3dad83
use swc_core::{ use swc_core::{
common::Mark, common::Mark,
ecma::{ ecma::{
ast::{CallExpr, Callee, Expr, Ident, Lit, MemberExpr, MemberProp, Prop, PropOrSpread}, ast::{
AssignExpr, AssignOp, AssignTarget, CallExpr, Callee, Expr, Ident, Lit, MemberExpr,
MemberProp, ObjectLit, Prop, PropOrSpread, SimpleAssignTarget,
},
utils::prop_name_eq, utils::prop_name_eq,
}, },
}; };
...@@ -98,6 +101,27 @@ pub(crate) fn define_property_sets_es_module(call: &CallExpr) -> bool { ...@@ -98,6 +101,27 @@ pub(crate) fn define_property_sets_es_module(call: &CallExpr) -> bool {
}) })
} }
/// The object literal of a `module.exports = { … }` whole-exports assignment,
/// whose properties are the module's named exports.
pub(crate) fn as_module_exports_object_literal(
n: &AssignExpr,
unresolved_mark: Mark,
) -> Option<&ObjectLit> {
if n.op != AssignOp::Assign {
return None;
}
let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &n.left else {
return None;
};
if !is_module_dot_exports(member, unresolved_mark) {
return None;
}
match unparen(&n.right) {
Expr::Object(obj) => Some(obj),
_ => None,
}
}
/// Whether `member` writes the module's own CommonJS exports: `exports.<x>`, /// Whether `member` writes the module's own CommonJS exports: `exports.<x>`,
/// `module.exports`, or `module.exports.<x>`. /// `module.exports`, or `module.exports.<x>`.
pub(crate) fn is_cjs_export_member(member: &MemberExpr, unresolved_mark: Mark) -> bool { pub(crate) fn is_cjs_export_member(member: &MemberExpr, unresolved_mark: Mark) -> bool {
......
...@@ -23,8 +23,8 @@ use crate::{ ...@@ -23,8 +23,8 @@ use crate::{
analyzer::{ analyzer::{
Bump, BumpVec, ConstantValue, ImportMap, JsValue, WellKnownFunctionKind, Bump, BumpVec, ConstantValue, ImportMap, JsValue, WellKnownFunctionKind,
cjs_ast::{ cjs_ast::{
as_exports_define_property, define_property_sets_es_module, is_exports_object, as_exports_define_property, as_module_exports_object_literal,
is_global, define_property_sets_es_module, is_exports_object, is_global,
}, },
graph::{ConditionalKind, Effect, EffectArg, EffectsBlock, EvalContext, VarGraph}, graph::{ConditionalKind, Effect, EffectArg, EffectsBlock, EvalContext, VarGraph},
is_unresolved_id, is_unresolved_id,
...@@ -659,8 +659,22 @@ mod analyzer_state { ...@@ -659,8 +659,22 @@ mod analyzer_state {
} }
pub(super) fn record_cjs_export(&mut self, name: RcStr, path: AstPath) { pub(super) fn record_cjs_export(&mut self, name: RcStr, path: AstPath) {
self.push_cjs_export(DroppableCjsExportAssignment::Write { name, path });
}
/// Records the named exports of a `module.exports = { … }` object literal. They
/// share `path` (the assignment); the code-gen removes each unused property.
pub(super) fn record_cjs_object_literal_exports(
&mut self,
names: Vec<RcStr>,
path: AstPath,
) {
self.push_cjs_export(DroppableCjsExportAssignment::ObjectLiteral { names, path });
}
fn push_cjs_export(&mut self, drop: DroppableCjsExportAssignment) {
if let Some(c) = &mut self.state.cjs_exports { if let Some(c) = &mut self.state.cjs_exports {
c.writes.push(DroppableCjsExportAssignment { name, path }); c.writes.push(drop);
} }
} }
...@@ -1356,6 +1370,67 @@ impl<'a> Analyzer<'a, '_> { ...@@ -1356,6 +1370,67 @@ impl<'a> Analyzer<'a, '_> {
} }
self.record_cjs_export(RcStr::from(name), as_parent_path(ast_path).into()); self.record_cjs_export(RcStr::from(name), as_parent_path(ast_path).into());
} }
/// Records the droppable named exports of a top-level `module.exports = { … }`
/// literal. A spread or computed key taints; `__esModule: true` sets the flag.
fn recognize_cjs_object_exports(
&mut self,
n: &AssignExpr,
ast_path: &AstNodePath<AstParentNodeRef<'_>>,
) {
// Only a top-level assignment defines the module's exports.
if self.is_in_fn() || self.is_in_nested_block_scope() {
self.taint_cjs_exports();
return;
}
let Some(obj) = as_module_exports_object_literal(n, self.eval_context.unresolved_mark)
else {
return;
};
let mut names = Vec::new();
for prop in &obj.props {
// A spread makes the export set unknowable.
let PropOrSpread::Prop(prop) = prop else {
self.taint_cjs_exports();
return;
};
// Only a data property has an eager value (preserved by the code-gen);
// getters/setters/methods have none and are removed outright.
let value = match &**prop {
Prop::KeyValue(kv) => Some(&*kv.value),
_ => None,
};
let name = match &**prop {
Prop::Shorthand(id) => RcStr::from(id.sym.as_str()),
Prop::KeyValue(KeyValueProp { key, .. })
| Prop::Getter(GetterProp { key, .. })
| Prop::Setter(SetterProp { key, .. })
| Prop::Method(MethodProp { key, .. }) => match key {
PropName::Ident(i) => RcStr::from(i.sym.as_str()),
PropName::Str(s) => RcStr::from(s.value.to_string_lossy().into_owned()),
// computed / numeric / bigint key → unknowable
_ => {
self.taint_cjs_exports();
return;
}
},
Prop::Assign(_) => continue, // should never happen for a literal
};
// `__esModule: true` is the interop marker, not a droppable export.
if &*name == "__esModule" {
if let Some(Expr::Lit(Lit::Bool(b))) = value.map(unparen)
&& b.value
{
self.set_cjs_has_es_module();
}
continue;
}
names.push(name);
}
if !names.is_empty() {
self.record_cjs_object_literal_exports(names, as_parent_path(ast_path).into());
}
}
} }
impl VisitAstPath for Analyzer<'_, '_> { impl VisitAstPath for Analyzer<'_, '_> {
...@@ -1388,6 +1463,11 @@ impl VisitAstPath for Analyzer<'_, '_> { ...@@ -1388,6 +1463,11 @@ impl VisitAstPath for Analyzer<'_, '_> {
// and visit the target inside a `cjs_export_target` scope so `exports` / `module` // and visit the target inside a `cjs_export_target` scope so `exports` / `module`
// don't taint the module (see `visit_ident`). // don't taint the module (see `visit_ident`).
let is_cjs_export = self.cjs_exports_enabled() && self.is_named_cjs_export_target(&n.left); let is_cjs_export = self.cjs_exports_enabled() && self.is_named_cjs_export_target(&n.left);
// `module.exports = { a, b, c }` — a whole-exports object literal whose
// properties are the module's named exports.
let is_cjs_object_export = !is_cjs_export
&& self.cjs_exports_enabled()
&& as_module_exports_object_literal(n, self.eval_context.unresolved_mark).is_some();
if is_cjs_export { if is_cjs_export {
self.maybe_recognize_cjs_export(n, ast_path); self.maybe_recognize_cjs_export(n, ast_path);
let mut ast_path = let mut ast_path =
...@@ -1395,6 +1475,15 @@ impl VisitAstPath for Analyzer<'_, '_> { ...@@ -1395,6 +1475,15 @@ impl VisitAstPath for Analyzer<'_, '_> {
self.with_cjs_export_target(|this| { self.with_cjs_export_target(|this| {
n.left.visit_children_with_ast_path(this, &mut ast_path) n.left.visit_children_with_ast_path(this, &mut ast_path)
}); });
} else if is_cjs_object_export {
self.recognize_cjs_object_exports(n, ast_path);
// Visit the `module.exports` target under the export-target guard so the
// `module` read doesn't taint the module.
let mut ast_path =
ast_path.with_guard(AstParentNodeRef::AssignExpr(n, AssignExprField::Left));
self.with_cjs_export_target(|this| {
n.left.visit_children_with_ast_path(this, &mut ast_path)
});
} else { } else {
// LHS. // LHS.
let mut ast_path = let mut ast_path =
...@@ -1424,8 +1513,9 @@ impl VisitAstPath for Analyzer<'_, '_> { ...@@ -1424,8 +1513,9 @@ impl VisitAstPath for Analyzer<'_, '_> {
{ {
let mut ast_path = let mut ast_path =
ast_path.with_guard(AstParentNodeRef::AssignExpr(n, AssignExprField::Right)); ast_path.with_guard(AstParentNodeRef::AssignExpr(n, AssignExprField::Right));
// A function assigned directly to a CommonJS export can see `exports` as `this`. // A function assigned directly to a CommonJS export can see `exports` as
if is_cjs_export && matches!(&*n.right, Expr::Fn(_)) { // `this`; likewise for functions inside a `module.exports = { … }` literal.
if (is_cjs_export && matches!(&*n.right, Expr::Fn(_))) || is_cjs_object_export {
self.with_cjs_export_value(|this| this.visit_expr(&n.right, &mut ast_path)); self.with_cjs_export_value(|this| this.visit_expr(&n.right, &mut ast_path));
} else { } else {
self.visit_expr(&n.right, &mut ast_path); self.visit_expr(&n.right, &mut ast_path);
......
use anyhow::Result; use anyhow::Result;
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
use swc_core::{ use swc_core::{
common::util::take::Take, common::{DUMMY_SP, util::take::Take},
ecma::{ ecma::{
ast::{CallExpr, Expr, ExprOrSpread, Lit, Prop, PropOrSpread}, ast::{
CallExpr, Expr, ExprOrSpread, Lit, ObjectLit, Prop, PropName, PropOrSpread,
SpreadElement,
},
utils::prop_name_eq, utils::prop_name_eq,
}, },
quote, quote,
...@@ -443,10 +446,9 @@ impl From<CjsRequireCacheAccess> for CodeGen { ...@@ -443,10 +446,9 @@ impl From<CjsRequireCacheAccess> for CodeGen {
} }
} }
/// Removes each named `exports.NAME = …` write (or `Object.defineProperty` /// Removes each named CommonJS export the module graph proved unused. Built by the
/// export) the module graph proved unused. Built by the analyzer for /// analyzer for statically-analyzable CommonJS modules; recognition happens inline
/// statically-analyzable CommonJS modules; recognition happens inline during the /// during the walk (see `analyzer::graph::visitor`).
/// walk (see `analyzer::graph::visitor`).
#[derive( #[derive(
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode, PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode,
)] )]
...@@ -457,15 +459,17 @@ pub struct CjsExportsDropCodeGen { ...@@ -457,15 +459,17 @@ pub struct CjsExportsDropCodeGen {
has_es_module: bool, has_es_module: bool,
} }
/// A single named CommonJS export write. /// A recognized CommonJS export declaration, and thus how it's dropped.
#[derive( #[derive(
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode, PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode,
)] )]
pub struct DroppableCjsExportAssignment { pub enum DroppableCjsExportAssignment {
pub name: RcStr, /// A standalone `exports.NAME = …` write or `Object.defineProperty(exports, …)`
/// Path to the write: an `exports.NAME = …` assignment expression or an /// call (the assignment is replaced by its value; the define call is removed).
/// `Object.defineProperty(exports, "NAME", …)` call. Write { name: RcStr, path: AstPath },
pub path: AstPath, /// A `module.exports = { … }` object literal. Every recognized property name
/// shares `path` (the assignment), so the literal is rewritten in one pass.
ObjectLiteral { names: Vec<RcStr>, path: AstPath },
} }
impl CjsExportsDropCodeGen { impl CjsExportsDropCodeGen {
...@@ -499,31 +503,50 @@ impl CjsExportsDropCodeGen { ...@@ -499,31 +503,50 @@ impl CjsExportsDropCodeGen {
// `exports.a = exports.b = 1` sound. // `exports.a = exports.b = 1` sound.
let mut visitors = Vec::new(); let mut visitors = Vec::new();
for drop in &self.drops { for drop in &self.drops {
if export_usage_info.is_export_used(&drop.name) { match drop {
continue; DroppableCjsExportAssignment::Write { name, path } => {
} if export_usage_info.is_export_used(name) {
visitors.push(create_visitor!( continue;
drop.path, }
visit_mut_expr, visitors.push(create_visitor!(path, visit_mut_expr, |expr: &mut Expr| {
|expr: &mut Expr| { match expr {
match expr { // `exports.NAME = <value>` → `<value>` (keep side effects).
// `exports.NAME = <value>` → `<value>` (keep side effects). Expr::Assign(assign) => {
Expr::Assign(assign) => { let value = assign.right.take();
let value = assign.right.take(); *expr = *value;
*expr = *value; }
} // `Object.defineProperty(exports, …)`: keep an eager
// `Object.defineProperty(exports, …)`: keep an eager // `value`'s side effects; a getter is lazy, drop the call.
// `value`'s side effects; a getter is lazy, drop the call. Expr::Call(call) => {
Expr::Call(call) => { *expr = match take_define_property_value(call) {
*expr = match take_define_property_value(call) { Some(value) => *value,
Some(value) => *value, None => quote!("0" as Expr),
None => quote!("0" as Expr), };
}; }
_ => {}
} }
_ => {} }));
}
DroppableCjsExportAssignment::ObjectLiteral { names, path } => {
let unused = names
.iter()
.filter(|name| !export_usage_info.is_export_used(name))
.cloned()
.collect::<Vec<_>>();
if unused.is_empty() {
continue;
} }
// `module.exports = { …, NAME: v, … }` → drop each unused `NAME`,
// keeping a data value's side effects in place via `...(void v)`.
visitors.push(create_visitor!(path, visit_mut_expr, |expr: &mut Expr| {
if let Expr::Assign(assign) = expr
&& let Expr::Object(obj) = &mut *assign.right
{
drop_object_literal_exports(obj, &unused);
}
}));
} }
)); }
} }
Ok(CodeGeneration::visitors(visitors)) Ok(CodeGeneration::visitors(visitors))
...@@ -548,6 +571,36 @@ fn take_define_property_value(call: &mut CallExpr) -> Option<Box<Expr>> { ...@@ -548,6 +571,36 @@ fn take_define_property_value(call: &mut CallExpr) -> Option<Box<Expr>> {
}) })
} }
/// Drops each of `names` from a `module.exports = { … }` literal.
fn drop_object_literal_exports(obj: &mut ObjectLit, names: &[RcStr]) {
let is_dropped = |key: &PropName| names.iter().any(|n| prop_name_eq(key, n));
obj.props = obj
.props
.take()
.into_iter()
.filter_map(|prop| {
let PropOrSpread::Prop(p) = &prop else {
return Some(prop);
};
match &**p {
// The value might have a side effect, preserve it by generating `...void (expr)`
Prop::KeyValue(kv) if is_dropped(&kv.key) => {
Some(PropOrSpread::Spread(SpreadElement {
dot3_token: DUMMY_SP,
expr: Box::new(quote!("void ($e)" as Expr, e: Expr = *kv.value.clone())),
}))
}
Prop::Shorthand(id) if names.iter().any(|n| id.sym.as_str() == &**n) => None,
Prop::Getter(g) if is_dropped(&g.key) => None,
Prop::Setter(s) if is_dropped(&s.key) => None,
Prop::Method(m) if is_dropped(&m.key) => None,
// A used export (or an already-rewritten spread) — keep as-is.
_ => Some(prop),
}
})
.collect();
}
impl From<CjsExportsDropCodeGen> for CodeGen { impl From<CjsExportsDropCodeGen> for CodeGen {
fn from(val: CjsExportsDropCodeGen) -> Self { fn from(val: CjsExportsDropCodeGen) -> Self {
CodeGen::CjsExportsDropCodeGen(val) CodeGen::CjsExportsDropCodeGen(val)
......
// `module.exports = { … }` with accessor/method exports. Unused getters, setters,
// and methods are removed outright — defining one has no side effect.
module.exports = {
used: 'used-value',
get usedGetter() {
return 'used-getter'
},
get unusedGetter() {
return 'unused-getter'
},
unusedMethod() {
return 'unused-method'
},
}
{
"removeUnusedImports": false,
"removeUnusedExports": true,
"cjsTreeShaking": true,
"treeShakingMode": "reexports-only"
}
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/17f0_snapshot_cjs-remove-unused-exports_object-literal-accessors_input_index_17fevvk.js",
{"otherChunks":["output/1jsg_tests_snapshot_cjs-remove-unused-exports_object-literal-accessors_input_02qvs87._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-accessors/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_cjs-remove-unused-exports_object-literal-accessors_input_02qvs87._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-accessors/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$cjs$2d$remove$2d$unused$2d$exports$2f$object$2d$literal$2d$accessors$2f$input$2f$lib$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-accessors/input/lib.js [test] (ecmascript)");
;
console.log(__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$cjs$2d$remove$2d$unused$2d$exports$2f$object$2d$literal$2d$accessors$2f$input$2f$lib$2e$js__$5b$test$5d$__$28$ecmascript$29$__["used"], __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$cjs$2d$remove$2d$unused$2d$exports$2f$object$2d$literal$2d$accessors$2f$input$2f$lib$2e$js__$5b$test$5d$__$28$ecmascript$29$__["usedGetter"]);
__turbopack_context__.s([]);
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-accessors/input/lib.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
// `module.exports = { … }` with accessor/method exports. Unused getters, setters,
// and methods are removed outright — defining one has no side effect.
module.exports = {
used: 'used-value',
get usedGetter () {
return 'used-getter';
}
};
}),
]);
//# sourceMappingURL=1jsg_tests_snapshot_cjs-remove-unused-exports_object-literal-accessors_input_02qvs87._.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-accessors/input/index.js"],"sourcesContent":["import { used, usedGetter } from './lib.js'\n\nconsole.log(used, usedGetter)\n"],"names":["console","log"],"mappings":"AAAA;;AAEAA,QAAQC,GAAG,CAAC,wPAAI,EAAE,8PAAU"}},
{"offset": {"line": 11, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-accessors/input/lib.js"],"sourcesContent":["// `module.exports = { … }` with accessor/method exports. Unused getters, setters,\n// and methods are removed outright — defining one has no side effect.\nmodule.exports = {\n used: 'used-value',\n get usedGetter() {\n return 'used-getter'\n },\n get unusedGetter() {\n return 'unused-getter'\n },\n unusedMethod() {\n return 'unused-method'\n },\n}\n"],"names":["module","exports","used","usedGetter"],"mappings":"AAAA,kFAAkF;AAClF,sEAAsE;AACtEA,OAAOC,OAAO,GAAG;IACfC,MAAM;IACN,IAAIC,cAAa;QACf,OAAO;IACT;AAOF"}}]
}
\ No newline at end of file
// `module.exports = { … }` with the `__esModule` interop marker. The marker must
// be kept (never dropped) and must set the ESM-interop flag; `unused` still drops.
module.exports = {
__esModule: true,
used: 'used-value',
unused: 'unused-value',
}
{
"removeUnusedImports": false,
"removeUnusedExports": true,
"cjsTreeShaking": true,
"treeShakingMode": "reexports-only"
}
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/17f0_snapshot_cjs-remove-unused-exports_object-literal-esmodule_input_index_1xbmk2f.js",
{"otherChunks":["output/1jsg_tests_snapshot_cjs-remove-unused-exports_object-literal-esmodule_input_0oqp2-_._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-esmodule/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_cjs-remove-unused-exports_object-literal-esmodule_input_0oqp2-_._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-esmodule/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$cjs$2d$remove$2d$unused$2d$exports$2f$object$2d$literal$2d$esmodule$2f$input$2f$lib$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-esmodule/input/lib.js [test] (ecmascript)");
;
console.log(__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$cjs$2d$remove$2d$unused$2d$exports$2f$object$2d$literal$2d$esmodule$2f$input$2f$lib$2e$js__$5b$test$5d$__$28$ecmascript$29$__["used"]);
__turbopack_context__.s([]);
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-esmodule/input/lib.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
// `module.exports = { … }` with the `__esModule` interop marker. The marker must
// be kept (never dropped) and must set the ESM-interop flag; `unused` still drops.
module.exports = {
__esModule: true,
used: 'used-value',
...void 'unused-value'
};
}),
]);
//# sourceMappingURL=1jsg_tests_snapshot_cjs-remove-unused-exports_object-literal-esmodule_input_0oqp2-_._.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-esmodule/input/index.js"],"sourcesContent":["import { used } from './lib.js'\n\nconsole.log(used)\n"],"names":["console","log"],"mappings":"AAAA;;AAEAA,QAAQC,GAAG,CAAC,uPAAI"}},
{"offset": {"line": 11, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-esmodule/input/lib.js"],"sourcesContent":["// `module.exports = { … }` with the `__esModule` interop marker. The marker must\n// be kept (never dropped) and must set the ESM-interop flag; `unused` still drops.\nmodule.exports = {\n __esModule: true,\n used: 'used-value',\n unused: 'unused-value',\n}\n"],"names":["module","exports","__esModule","used"],"mappings":"AAAA,iFAAiF;AACjF,mFAAmF;AACnFA,OAAOC,OAAO,GAAG;IACfC,YAAY;IACZC,MAAM;YACE;AACV"}}]
}
\ No newline at end of file
import { used, usedFn, usedShort } from './lib.js'
console.log(used, usedFn(), usedShort)
// Hand-written / transpiled CJS: named exports declared as a whole-object
// `module.exports = { … }` literal. An unused data property keeps its value's
// side effects in place via `...(void …)`; an unused shorthand (a plain ident
// read) is removed outright.
const usedShort = 'used-short'
const unusedShort = 'unused-short'
module.exports = {
used: 'used-value',
unused: 'unused-value',
usedShort,
unusedShort,
usedFn: function () {
return 'used-fn'
},
unusedFn: function () {
return 'unused-fn'
},
}
{
"removeUnusedImports": false,
"removeUnusedExports": true,
"cjsTreeShaking": true,
"treeShakingMode": "reexports-only"
}
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1ece_tests_snapshot_cjs-remove-unused-exports_object-literal_input_index_1dbi46m.js",
{"otherChunks":["output/1jsg_tests_snapshot_cjs-remove-unused-exports_object-literal_input_0pihkv0._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_cjs-remove-unused-exports_object-literal_input_0pihkv0._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$cjs$2d$remove$2d$unused$2d$exports$2f$object$2d$literal$2f$input$2f$lib$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal/input/lib.js [test] (ecmascript)");
;
console.log(__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$cjs$2d$remove$2d$unused$2d$exports$2f$object$2d$literal$2f$input$2f$lib$2e$js__$5b$test$5d$__$28$ecmascript$29$__["used"], (0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$cjs$2d$remove$2d$unused$2d$exports$2f$object$2d$literal$2f$input$2f$lib$2e$js__$5b$test$5d$__$28$ecmascript$29$__["usedFn"])(), __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$cjs$2d$remove$2d$unused$2d$exports$2f$object$2d$literal$2f$input$2f$lib$2e$js__$5b$test$5d$__$28$ecmascript$29$__["usedShort"]);
__turbopack_context__.s([]);
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal/input/lib.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
// Hand-written / transpiled CJS: named exports declared as a whole-object
// `module.exports = { … }` literal. An unused data property keeps its value's
// side effects in place via `...(void …)`; an unused shorthand (a plain ident
// read) is removed outright.
const usedShort = 'used-short';
const unusedShort = 'unused-short';
module.exports = {
used: 'used-value',
...void 'unused-value',
usedShort,
usedFn: function() {
return 'used-fn';
},
...void function() {
return 'unused-fn';
}
};
}),
]);
//# sourceMappingURL=1jsg_tests_snapshot_cjs-remove-unused-exports_object-literal_input_0pihkv0._.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal/input/index.js"],"sourcesContent":["import { used, usedFn, usedShort } from './lib.js'\n\nconsole.log(used, usedFn(), usedShort)\n"],"names":["console","log"],"mappings":"AAAA;;AAEAA,QAAQC,GAAG,CAAC,2OAAI,EAAE,IAAA,6OAAM,KAAI,gPAAS"}},
{"offset": {"line": 11, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal/input/lib.js"],"sourcesContent":["// Hand-written / transpiled CJS: named exports declared as a whole-object\n// `module.exports = { … }` literal. An unused data property keeps its value's\n// side effects in place via `...(void …)`; an unused shorthand (a plain ident\n// read) is removed outright.\nconst usedShort = 'used-short'\nconst unusedShort = 'unused-short'\nmodule.exports = {\n used: 'used-value',\n unused: 'unused-value',\n usedShort,\n unusedShort,\n usedFn: function () {\n return 'used-fn'\n },\n unusedFn: function () {\n return 'unused-fn'\n },\n}\n"],"names":["usedShort","unusedShort","module","exports","used","usedFn"],"mappings":"AAAA,0EAA0E;AAC1E,8EAA8E;AAC9E,8EAA8E;AAC9E,6BAA6B;AAC7B,MAAMA,YAAY;AAClB,MAAMC,cAAc;AACpBC,OAAOC,OAAO,GAAG;IACfC,MAAM;YACE;IACRJ;IAEAK,QAAQ;QACN,OAAO;IACT;YACU;QACR,OAAO;IACT;AACF"}}]
}
\ No newline at end of file
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