Skip to content

Commit 3658eca

Browse files
feat: resolve imported ESM bindings by name in a debugger
Imported bindings compile to a namespace read, so a debugger's console and watch expressions cannot resolve the name the source uses (#3957). Two complementary halves, both semantics-preserving: `optimization.localImportBindings` (on in development) declares a real local variable for an imported name wherever that is observationally equal to the live binding: a namespace object, whose identity never changes, and a named import of a top-level `const` or an `export default` expression, which the language pins to one value. A module read from inside its own evaluation cycle, or accepted by `module.hot.accept` (where an update re-runs the import statement rather than the module body), keeps reading through the namespace. A `-scopes` devtool suffix emits the ECMA-426 "Scopes" field, naming for every remaining binding the generated expression it reads. It changes no emitted code and costs bytes only in the map.
1 parent 902123d commit 3658eca

49 files changed

Lines changed: 1409 additions & 30 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": minor
3+
---
4+
5+
Resolve imported ESM bindings by name in a debugger, via locals and `scopes`.

‎declarations/WebpackOptions.d.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2322,6 +2322,11 @@ export interface Optimization {
23222322
* Creates a module-internal dependency graph for top level symbols, exports and imports, to improve unused exports detection.
23232323
*/
23242324
innerGraph?: boolean;
2325+
/**
2326+
* Read an imported ESM binding into a local variable of the same name wherever that is observationally equal to the live binding, so a debugger resolves it under the name the source uses.
2327+
* @since 5.111.0
2328+
*/
2329+
localImportBindings?: boolean;
23252330
/**
23262331
* Rename exports when possible to generate shorter code (depends on optimization.usedExports and optimization.providedExports, true/"deterministic": generate short deterministic names optimized for caching, "size": generate the shortest possible names).
23272332
*/
@@ -4909,6 +4914,11 @@ export interface OptimizationNormalized {
49094914
* Creates a module-internal dependency graph for top level symbols, exports and imports, to improve unused exports detection.
49104915
*/
49114916
innerGraph?: boolean;
4917+
/**
4918+
* Read an imported ESM binding into a local variable of the same name wherever that is observationally equal to the live binding, so a debugger resolves it under the name the source uses.
4919+
* @since 5.111.0
4920+
*/
4921+
localImportBindings?: boolean;
49124922
/**
49134923
* Rename exports when possible to generate shorter code (depends on optimization.usedExports and optimization.providedExports, true/"deterministic": generate short deterministic names optimized for caching, "size": generate the shortest possible names).
49144924
*/

‎declarations/plugins/SourceMapDevToolPlugin.d.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,11 @@ export interface SourceMapDevToolPluginOptions {
7878
* Provide a custom public path for the SourceMapping comment.
7979
*/
8080
publicPath?: string;
81+
/**
82+
* Emit the 'scopes' field, which tells a debugger the generated expression each imported ESM binding reads, so it resolves under the name the source uses.
83+
* @since 5.111.0
84+
*/
85+
scopes?: boolean;
8186
/**
8287
* Provide a custom value for the 'sourceRoot' property in the SourceMap.
8388
*/

‎lib/DependencyTemplate.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
* @property {ConcatenationScope=} concatenationScope when in a concatenated module, information about other concatenated modules
3838
* @property {CodeGenerationResults} codeGenerationResults the code generation results
3939
* @property {InitFragment<GenerateContext>[]} chunkInitFragments chunkInitFragments
40+
* @property {Map<string, string>=} importBindings what each imported binding of the current module reads, by its name in the source, for the source map `scopes` field
4041
*/
4142

4243
/**

‎lib/EvalSourceMapDevToolPlugin.js‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
1414
const ConcatenatedModule = require("./optimize/ConcatenatedModule");
1515
const generateDebugId = require("./util/generateDebugId");
1616
const { makePathsAbsolute } = require("./util/identifier");
17+
const {
18+
addScopesToSourceMap,
19+
enableImportBindingScopes
20+
} = require("./util/sourceMapScopes");
1721

1822
/** @import { RawSourceMap, Source } from "webpack-sources" */
1923
/**
@@ -84,6 +88,9 @@ class EvalSourceMapDevToolPlugin {
8488
apply(compiler) {
8589
const options = this.options;
8690
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
91+
if (options.scopes) {
92+
enableImportBindingScopes(compilation.moduleGraph);
93+
}
8794
const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
8895
new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
8996
const matchModule = ModuleFilenameHelpers.matchObject.bind(
@@ -211,6 +218,27 @@ class EvalSourceMapDevToolPlugin {
211218
sourceMap.debugId = generateDebugId(content, sourceMap.file);
212219
}
213220

221+
const { codeGenerationResults } = compilation;
222+
if (options.scopes && codeGenerationResults) {
223+
// The clone above shares `names` with the source's own map, and
224+
// encoding appends to it.
225+
sourceMap.names = sourceMap.names ? [...sourceMap.names] : [];
226+
addScopesToSourceMap(sourceMap, (sourceIndex) => {
227+
const module = modules[sourceIndex];
228+
if (
229+
typeof module === "string" ||
230+
!codeGenerationResults.has(module, chunk.runtime)
231+
) {
232+
return;
233+
}
234+
return codeGenerationResults.getData(
235+
module,
236+
chunk.runtime,
237+
"importBindings"
238+
);
239+
});
240+
}
241+
214242
const footer = `${this.sourceMapComment.replace(
215243
/\[url\]/g,
216244
`data:application/json;charset=utf-8;base64,${Buffer.from(

‎lib/InitFragment.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,5 +207,6 @@ InitFragment.STAGE_HARMONY_IMPORTS = 40;
207207
InitFragment.STAGE_PROVIDES = 50;
208208
InitFragment.STAGE_ASYNC_DEPENDENCIES = 60;
209209
InitFragment.STAGE_ASYNC_HARMONY_IMPORTS = 70;
210+
InitFragment.STAGE_HARMONY_IMPORT_BINDINGS = 80;
210211

211212
module.exports = InitFragment;

‎lib/NormalModule.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1649,6 +1649,7 @@ class NormalModule extends Module {
16491649
topLevelDeclarations: undefined,
16501650
pureFunctions: undefined,
16511651
inlineExports: undefined,
1652+
stableExports: undefined,
16521653
moduleConcatenationBailout: undefined,
16531654
moduleConcatenationRootBailout: undefined,
16541655
needCreateRequire: undefined,

‎lib/SourceMapDevToolPlugin.js‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ const createHash = require("./util/createHash");
1616
const { dirname, relative } = require("./util/fs");
1717
const generateDebugId = require("./util/generateDebugId");
1818
const { makePathsAbsolute } = require("./util/identifier");
19+
const {
20+
addScopesToSourceMap,
21+
enableImportBindingScopes
22+
} = require("./util/sourceMapScopes");
1923

2024
/** @import { MapOptions, Source, RawSourceMap } from "webpack-sources" */
2125
/**
@@ -279,6 +283,7 @@ class SourceMapDevToolPlugin {
279283
options.columns !== false,
280284
Boolean(options.noSources),
281285
Boolean(options.debugIds),
286+
Boolean(options.scopes),
282287
options.sourceRoot || "",
283288
toCacheKeyValue(options.ignoreList),
284289
options.publicPath || "",
@@ -324,6 +329,9 @@ class SourceMapDevToolPlugin {
324329
);
325330

326331
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
332+
if (options.scopes) {
333+
enableImportBindingScopes(compilation.moduleGraph);
334+
}
327335
new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
328336

329337
// All SourceMapDevToolPlugin instances on the same compilation share
@@ -764,6 +772,29 @@ class SourceMapDevToolPlugin {
764772
if (debugIdValue !== undefined) {
765773
outputSourceMap.debugId = debugIdValue;
766774
}
775+
const { codeGenerationResults } = compilation;
776+
if (options.scopes && codeGenerationResults) {
777+
// The spread above shares `names` with a map a
778+
// `SourceMapSource` may hold, and encoding appends to it.
779+
outputSourceMap.names = sourceMap.names
780+
? [...sourceMap.names]
781+
: [];
782+
const runtime = chunk && chunk.runtime;
783+
addScopesToSourceMap(outputSourceMap, (sourceIndex) => {
784+
const module = modules[sourceIndex];
785+
if (
786+
typeof module === "string" ||
787+
!codeGenerationResults.has(module, runtime)
788+
) {
789+
return;
790+
}
791+
return codeGenerationResults.getData(
792+
module,
793+
runtime,
794+
"importBindings"
795+
);
796+
});
797+
}
767798

768799
if (sourceMapFilename) {
769800
// External `.map` file: hold the serialized map as a

‎lib/WebpackOptionsApply.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,7 @@ class WebpackOptionsApply extends OptionsApply {
453453
const moduleMaps = use.includes("module");
454454
const noSources = use.includes("nosources");
455455
const debugIds = use.includes("debugids");
456+
const scopes = use.includes("scopes");
456457
const Plugin = evalWrapped
457458
? require("./EvalSourceMapDevToolPlugin")
458459
: require("./SourceMapDevToolPlugin");
@@ -475,7 +476,8 @@ class WebpackOptionsApply extends OptionsApply {
475476
columns: !cheap,
476477
noSources,
477478
namespace: options.output.devtoolNamespace,
478-
debugIds
479+
debugIds,
480+
scopes
479481
}).apply(compiler);
480482
} else if (use.includes("eval")) {
481483
const EvalDevToolModulePlugin = require("./EvalDevToolModulePlugin");
@@ -756,6 +758,11 @@ class WebpackOptionsApply extends OptionsApply {
756758
inlineExports: options.optimization.inlineExports
757759
}).apply(compiler);
758760

761+
if (options.optimization.localImportBindings) {
762+
const LocalImportBindingsPlugin = require("./optimize/LocalImportBindingsPlugin");
763+
764+
new LocalImportBindingsPlugin().apply(compiler);
765+
}
759766
if (options.optimization.mangleExports) {
760767
const MangleExportsPlugin = require("./optimize/MangleExportsPlugin");
761768

‎lib/config/defaults.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ const {
171171
* mangleExports: NonNullable<Optimization["mangleExports"]>,
172172
* innerGraph: NonNullable<Optimization["innerGraph"]>,
173173
* inlineExports: NonNullable<Optimization["inlineExports"]>,
174+
* localImportBindings: NonNullable<Optimization["localImportBindings"]>,
174175
* concatenateModules: NonNullable<Optimization["concatenateModules"]>,
175176
* avoidEntryIife: NonNullable<Optimization["avoidEntryIife"]>,
176177
* emitOnErrors: NonNullable<Optimization["emitOnErrors"]>,
@@ -2459,6 +2460,7 @@ const applyOptimizationDefaults = (
24592460
D(optimization, "usedExports", production);
24602461
D(optimization, "innerGraph", production);
24612462
D(optimization, "inlineExports", production);
2463+
D(optimization, "localImportBindings", development);
24622464
D(optimization, "mangleExports", production);
24632465
D(optimization, "concatenateModules", production);
24642466
D(optimization, "avoidEntryIife", production);

0 commit comments

Comments
 (0)