Unverified Commit eb7beb59 authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Drop dead `require()` calls (#95718)

This PR adds support for `turbopackRemoveUnusedImports` in CJS modules.
If modules are side-effect free and their imports are unused we do the
following re-writes:

```
require('./pure')          →   0;
console.log('x')               console.log('x')
```

```
const x = require('./pure')   →   const x = 0
```

```
const dead = require('./pure'), keep = 'v'   →   const dead = 0, keep = 'v'
```

```
const {} = require('./pure')   →   const {} = 0
```

```
if (cond) require('./pure')   →   if (cond) 0; 
```

SWC should then drop the 0.
parent 1f04d8ff
......@@ -567,10 +567,13 @@ mod analyzer_state {
pub(in crate::analyzer::graph) fn enable_require_usage(&mut self, imports: &ImportMap) {
let cjs_imports = imports.cjs_imports();
self.data.require_usage = cjs_imports.resolved.clone();
// Seed each namespace binding as `Evaluation`; a binding that's never
// read keeps that (only the target's side effects matter), while a
// member read upgrades it to `PartialNamespaceObject` below.
for span in cjs_imports.bindings.values() {
self.data
.require_usage
.insert(*span, ExportUsage::PartialNamespaceObject(SmallVec::new()));
.insert(*span, ExportUsage::Evaluation);
}
self.state.require_bindings = Some(cjs_imports.bindings.clone());
}
......@@ -596,13 +599,21 @@ mod analyzer_state {
return;
};
match member {
Some(name) => {
if let ExportUsage::PartialNamespaceObject(names) = usage
&& !names.contains(&name)
{
Some(name) => match usage {
ExportUsage::PartialNamespaceObject(names) => {
if !names.contains(&name) {
names.push(name);
}
}
// First member read of an otherwise-unused binding.
ExportUsage::Evaluation => {
let mut names = SmallVec::new();
names.push(name);
*usage = ExportUsage::PartialNamespaceObject(names);
}
}
// Already escaped to the whole namespace.
_ => {}
},
None => *usage = ExportUsage::All,
}
}
......
......@@ -943,6 +943,8 @@ impl Analyzer<'_> {
}
Pat::Object(_) => {
let usage = match extract_names_from_object_pat(&n.name) {
// `const {} = require(...)`: no members read → evaluation only.
Some(names) if names.is_empty() => ExportUsage::Evaluation,
Some(names) => ExportUsage::PartialNamespaceObject(names),
None => ExportUsage::All,
};
......@@ -1455,6 +1457,17 @@ impl Visit for Analyzer<'_> {
node.visit_children_with(self);
}
fn visit_expr_stmt(&mut self, node: &ExprStmt) {
// A bare `require("…")` statement discards its result → evaluation only.
if let Some(call) = as_require_call(&node.expr, self.unresolved_mark) {
self.data
.cjs_imports
.resolved
.insert(call.span.lo, ExportUsage::Evaluation);
}
node.visit_children_with(self);
}
fn visit_update_expr(&mut self, node: &UpdateExpr) {
if let Some(key) = node.arg.as_ident() {
// node.arg can also be a member expression
......
......@@ -102,6 +102,7 @@ pub struct CjsRequireAssetReference {
chunking_type_attribute: Option<SpecifiedChunkingType>,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
usage: ExportUsage,
cjs_tree_shaking: bool,
}
impl CjsRequireAssetReference {
......@@ -113,6 +114,7 @@ impl CjsRequireAssetReference {
chunking_type_attribute: Option<SpecifiedChunkingType>,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
usage: ExportUsage,
cjs_tree_shaking: bool,
) -> Self {
CjsRequireAssetReference {
origin,
......@@ -122,6 +124,7 @@ impl CjsRequireAssetReference {
chunking_type_attribute,
resolve_override,
usage,
cjs_tree_shaking,
}
}
}
......@@ -198,6 +201,22 @@ impl CjsRequireAssetReferenceCodeGen {
) -> Result<CodeGeneration> {
let reference = self.reference.await?;
// This `require()` is in `unused_references`: its result is unused and
// the target is side-effect free. Replace the call with a placeholder
// at the expression level.
if reference.cjs_tree_shaking
&& chunking_context
.unused_references()
.contains_key(&ResolvedVc::upcast(self.reference))
.await?
{
let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| {
// `const {a,b} = 0;` is a clever way to assign undefined to all the variables
*expr = quote!("0" as Expr);
});
return Ok(CodeGeneration::visitors(vec![visitor]));
}
let pm = PatternMapping::resolve_request(
*reference.request,
*reference.origin,
......
......@@ -459,6 +459,7 @@ struct AnalysisState<'a> {
// the object allocation.
first_webpack_exports_info: bool,
module_fragments_enabled: bool,
cjs_tree_shaking: bool,
import_externals: bool,
ignore_dynamic_requests: bool,
url_rewrite_behavior: Option<UrlRewriteBehavior>,
......@@ -859,6 +860,7 @@ async fn analyze_ecmascript_module_internal(
first_import_meta: true,
first_webpack_exports_info: true,
module_fragments_enabled: options.module_fragments_enabled,
cjs_tree_shaking: options.cjs_tree_shaking,
import_externals: options.import_externals,
ignore_dynamic_requests: options.ignore_dynamic_requests,
url_rewrite_behavior: options.url_rewrite_behavior,
......@@ -2139,6 +2141,7 @@ where
attributes.chunking_type,
resolve_override,
call_usage.clone(),
state.cjs_tree_shaking,
),
ast_path.to_vec().into(),
);
......@@ -2192,6 +2195,7 @@ where
attributes.chunking_type,
None,
call_usage.clone(),
state.cjs_tree_shaking,
),
ast_path.to_vec().into(),
);
......
import { keep } from './lib.js'
it('keeps a sibling declarator when an unused require shares its declaration', () => {
expect(keep).toBe('kept')
})
// `dead` is an unused require binding that shares its declaration with `keep`.
// Dropping the unused require must not delete the sibling `keep` declarator; the
// call is replaced in place (`const dead = 0, keep = 'kept'`).
const dead = require('./pure.js'),
keep = 'kept'
exports.keep = keep
// Has a real side effect, so a bare `require('./effect.js')` must be kept.
globalThis.__cjs_effect_ran = true
exports.unused = 'value'
globalThis.__cjs_effect_ran = false
require('./effect.js')
it('keeps a bare require to a side-effectful module', () => {
expect(globalThis.__cjs_effect_ran).toBe(true)
})
// The result of this bare require is discarded, and the target is side-effect
// free, so the `require(...)` call is replaced with a `0` placeholder (later
// removed by minification) instead of loading the module.
require('./pure.js')
console.log('kept')
{
"removeUnusedImports": true,
"removeUnusedExports": true,
"cjsTreeShaking": true,
"treeShakingMode": "reexports-only"
}
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1ece_tests_snapshot_cjs-remove-unused-imports_bare-require_input_index_1ro4g9b.js",
{"otherChunks":["output/1jsg_tests_snapshot_cjs-remove-unused-imports_bare-require_input_index_134e7q6.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-imports/bare-require/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-imports_bare-require_input_index_134e7q6.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-imports/bare-require/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
// The result of this bare require is discarded, and the target is side-effect
// free, so the `require(...)` call is replaced with a `0` placeholder (later
// removed by minification) instead of loading the module.
0;
console.log('kept');
}),
]);
//# sourceMappingURL=1jsg_tests_snapshot_cjs-remove-unused-imports_bare-require_input_index_134e7q6.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 3, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-imports/bare-require/input/index.js"],"sourcesContent":["// The result of this bare require is discarded, and the target is side-effect\n// free, so the `require(...)` call is replaced with a `0` placeholder (later\n// removed by minification) instead of loading the module.\nrequire('./pure.js')\n\nconsole.log('kept')\n"],"names":["console","log"],"mappings":"AAAA,8EAA8E;AAC9E,6EAA6E;AAC7E,0DAA0D;;AAG1DA,QAAQC,GAAG,CAAC"}}]
}
\ 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