Skip to content

Commit c04058e

Browse files
docs(examples): show how to expose a module to the global object (#21952)
* docs(examples): keep the add-exports plugin in the configuration It is the shape the add-imports example settled on for the same hook: the plugin is a function next to the table it reads, so no `internals/` file stands between the reader and the configuration. * docs(examples): show how to expose a module to the global object A script that is not part of the bundle reads what it needs off the global object, and putting it there is one appended line - the same `processResult` hook the add-exports and add-imports examples use. webpack parses the line as the module's own, so the reference is analyzed like any other: in production both modules are hoisted into the entry, the exposed bindings are renamed and the assignments rename with them, while `PI`, which nothing reads, is shaken out. * docs(examples): make the processResult plugins classes A class with `apply()` is what a webpack plugin is, and what the three examples on this hook now show - the data it works from passed to its constructor, so the configuration reads as the table it is. No function wrapper stands in for the class in any of them. The emitted output of all three is byte for byte what it was. * docs(examples): say which mode the expose-global output is from The renaming, hoisting and shaking the prose points at are production's; the bundle printed under it is the unoptimized one, which keeps both exports. And nothing rewrites the appended `globalThis` - a target without it is one where the line itself has to say `self` or `window`. * docs(examples): say which mode the add-exports output is from Production folds `add(PI, 1)` to `3.14 + 1` - the inlining and hoisting the prose points at - while the bundle printed under it is the unoptimized one, which keeps both exports and calls through the import.
1 parent 78aaae3 commit c04058e

12 files changed

Lines changed: 533 additions & 132 deletions

File tree

‎examples/add-exports/README.md‎

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,20 @@
22

33
Some files export nothing: a legacy script that only defines globals, a vendored file, a bundle that was never written as a module. Appending the exports before webpack parses the file is enough — the parser reads them as the module's own.
44

5-
No loader is needed for that. `NormalModule`'s `processResult` hook hands a plugin what the loaders produced — source, source map and any preparsed AST — and takes back a replacement.
5+
No loader is needed for that. `NormalModule`'s `processResult` hook hands a plugin what the loaders produced — source, source map and any preparsed AST — and takes back a replacement. It is the same hook [adding imports](../add-imports) uses, from the other end of the file, and it is small enough to keep in the configuration.
66

7-
Which format to append is the module's own, and the two are not equivalent. `export { … }` is what makes a file an ES module, exactly as it would be in the source, so those exports are analyzable: below, `math.js` has its `PI` inlined into the call site and its `add` hoisted into the entry, like any `export` webpack reads. `module.exports = …` keeps the file the script it is, and webpack treats it as it treats any module whose whole exports object is assigned a value — `legacy-global.js` below keeps runtime-defined exports and is not analyzed that way. Prefer the ES module form where the file tolerates it.
7+
Which format to append is the module's own, and the two are not equivalent. `export { … }` is what makes a file an ES module, exactly as it would be in the source, so those exports are analyzable: under `mode: "production"`, `math.js` has its `PI` inlined into the call site and its `add` hoisted into the entry, like any `export` webpack reads, and the unoptimized output below keeps both. `module.exports = …` keeps the file the script it is, and webpack treats it as it treats any module whose whole exports object is assigned a value — `legacy-global.js` below keeps runtime-defined exports and is not analyzed that way. Prefer the ES module form where the file tolerates it.
88

99
Appending moves nothing before it, so the source map is still valid; a preparsed AST is dropped, because webpack would otherwise parse that instead of the appended code.
1010

11-
# internals/add-exports-plugin.js
11+
# webpack.config.js
1212

1313
```javascript
1414
"use strict";
1515

16-
const { NormalModule } = require("../../../");
16+
const { NormalModule } = require("../../");
1717

18-
/** @import { Compiler } from "webpack" */
18+
/** @import { Compiler } from "../../" */
1919

2020
const PLUGIN_NAME = "AddExportsPlugin";
2121

@@ -59,17 +59,7 @@ class AddExportsPlugin {
5959
}
6060
}
6161

62-
module.exports = AddExportsPlugin;
63-
```
64-
65-
# webpack.config.js
66-
67-
```javascript
68-
"use strict";
69-
70-
const AddExportsPlugin = require("./internals/add-exports-plugin");
71-
72-
/** @type {import("webpack").Configuration} */
62+
/** @type {import("../../").Configuration} */
7363
module.exports = {
7464
plugins: [
7565
new AddExportsPlugin([

‎examples/add-exports/template.md‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,12 @@
22

33
Some files export nothing: a legacy script that only defines globals, a vendored file, a bundle that was never written as a module. Appending the exports before webpack parses the file is enough — the parser reads them as the module's own.
44

5-
No loader is needed for that. `NormalModule`'s `processResult` hook hands a plugin what the loaders produced — source, source map and any preparsed AST — and takes back a replacement.
5+
No loader is needed for that. `NormalModule`'s `processResult` hook hands a plugin what the loaders produced — source, source map and any preparsed AST — and takes back a replacement. It is the same hook [adding imports](../add-imports) uses, from the other end of the file, and it is small enough to keep in the configuration.
66

7-
Which format to append is the module's own, and the two are not equivalent. `export { … }` is what makes a file an ES module, exactly as it would be in the source, so those exports are analyzable: below, `math.js` has its `PI` inlined into the call site and its `add` hoisted into the entry, like any `export` webpack reads. `module.exports = …` keeps the file the script it is, and webpack treats it as it treats any module whose whole exports object is assigned a value — `legacy-global.js` below keeps runtime-defined exports and is not analyzed that way. Prefer the ES module form where the file tolerates it.
7+
Which format to append is the module's own, and the two are not equivalent. `export { … }` is what makes a file an ES module, exactly as it would be in the source, so those exports are analyzable: under `mode: "production"`, `math.js` has its `PI` inlined into the call site and its `add` hoisted into the entry, like any `export` webpack reads, and the unoptimized output below keeps both. `module.exports = …` keeps the file the script it is, and webpack treats it as it treats any module whose whole exports object is assigned a value — `legacy-global.js` below keeps runtime-defined exports and is not analyzed that way. Prefer the ES module form where the file tolerates it.
88

99
Appending moves nothing before it, so the source map is still valid; a preparsed AST is dropped, because webpack would otherwise parse that instead of the appended code.
1010

11-
# internals/add-exports-plugin.js
12-
13-
```javascript
14-
_{{internals/add-exports-plugin.js}}_
15-
```
16-
1711
# webpack.config.js
1812

1913
```javascript

‎examples/add-exports/webpack.config.js‎

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,52 @@
11
"use strict";
22

3-
const AddExportsPlugin = require("./internals/add-exports-plugin");
3+
const { NormalModule } = require("../../");
44

5-
/** @type {import("webpack").Configuration} */
5+
/** @import { Compiler } from "../../" */
6+
7+
const PLUGIN_NAME = "AddExportsPlugin";
8+
9+
/**
10+
* Appends exports to modules which have none, before webpack parses them, so
11+
* the exports are read as the module's own.
12+
*/
13+
class AddExportsPlugin {
14+
/**
15+
* Creates an instance of AddExportsPlugin.
16+
* @param {[RegExp, string][]} exports pairs of a resource condition and the code to append
17+
*/
18+
constructor(exports) {
19+
this.exports = exports;
20+
}
21+
22+
/**
23+
* Applies the plugin by registering its hooks on the compiler.
24+
* @param {Compiler} compiler the compiler instance
25+
* @returns {void}
26+
*/
27+
apply(compiler) {
28+
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
29+
NormalModule.getCompilationHooks(compilation).processResult.tap(
30+
PLUGIN_NAME,
31+
(result, module) => {
32+
const [source, sourceMap] = result;
33+
for (const [test, code] of this.exports) {
34+
// a global or sticky pattern keeps its lastIndex between calls,
35+
// which would skip the next module it is tested against
36+
test.lastIndex = 0;
37+
if (!module.resource || !test.test(module.resource)) continue;
38+
// appending moves nothing before it, so the source map still fits;
39+
// a preparsed ast would be parsed instead of the appended code
40+
return [`${source}\n${code}`, sourceMap, undefined];
41+
}
42+
return result;
43+
}
44+
);
45+
});
46+
}
47+
}
48+
49+
/** @type {import("../../").Configuration} */
650
module.exports = {
751
plugins: [
852
new AddExportsPlugin([

‎examples/add-imports/README.md‎

Lines changed: 59 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -27,61 +27,73 @@ const PLUGIN_NAME = "AddImportsPlugin";
2727
// the module sloppy, so the code goes after one.
2828
const DIRECTIVE = /^\s*(["'])use strict\1;?/;
2929

30-
/** @type {[RegExp, { before?: string, after?: string }][]} */
31-
const imports = [
32-
[
33-
/legacy-lib\.js$/,
34-
{
35-
// the polyfill for its side effects, `$` as a binding the script reads,
36-
// and a wrapper so its top-level `this` is the global object
37-
before:
38-
'require("./polyfill.js");var $ = require("./jquery.js");(function () {',
39-
after: "}).call(globalThis);"
40-
}
41-
]
42-
];
43-
4430
/**
4531
* Puts code around modules which read values they never import, before webpack
4632
* parses them, so the imports are read as the module's own.
47-
* @param {Compiler} compiler the compiler instance
48-
* @returns {void}
4933
*/
50-
const addImports = (compiler) => {
51-
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
52-
NormalModule.getCompilationHooks(compilation).processResult.tap(
53-
PLUGIN_NAME,
54-
(result, module) => {
55-
const [source, sourceMap] = result;
56-
for (const [test, { before = "", after = "" }] of imports) {
57-
// a global or sticky pattern keeps its lastIndex between calls,
58-
// which would skip the next module it is tested against
59-
test.lastIndex = 0;
60-
if (!module.resource || !test.test(module.resource)) continue;
61-
// a file no loader touched arrives as the buffer webpack read
62-
const code =
63-
typeof source === "string" ? source : source.toString("utf8");
64-
const directive = DIRECTIVE.exec(code);
65-
const at = directive ? directive[0].length : 0;
66-
// a directive its source left unterminated would run into `before`
67-
const end = directive && !directive[0].endsWith(";") ? ";" : "";
68-
// no newline after `before`: one would shift every line below it out
69-
// of the source map; a preparsed ast would be parsed instead of this
70-
return [
71-
`${code.slice(0, at)}${end}${before}${code.slice(at)}\n${after}`,
72-
sourceMap,
73-
undefined
74-
];
34+
class AddImportsPlugin {
35+
/**
36+
* Creates an instance of AddImportsPlugin.
37+
* @param {[RegExp, { before?: string, after?: string }][]} imports pairs of a resource condition and the code to put around it
38+
*/
39+
constructor(imports) {
40+
this.imports = imports;
41+
}
42+
43+
/**
44+
* Applies the plugin by registering its hooks on the compiler.
45+
* @param {Compiler} compiler the compiler instance
46+
* @returns {void}
47+
*/
48+
apply(compiler) {
49+
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
50+
NormalModule.getCompilationHooks(compilation).processResult.tap(
51+
PLUGIN_NAME,
52+
(result, module) => {
53+
const [source, sourceMap] = result;
54+
for (const [test, { before = "", after = "" }] of this.imports) {
55+
// a global or sticky pattern keeps its lastIndex between calls,
56+
// which would skip the next module it is tested against
57+
test.lastIndex = 0;
58+
if (!module.resource || !test.test(module.resource)) continue;
59+
// a file no loader touched arrives as the buffer webpack read
60+
const code =
61+
typeof source === "string" ? source : source.toString("utf8");
62+
const directive = DIRECTIVE.exec(code);
63+
const at = directive ? directive[0].length : 0;
64+
// a directive its source left unterminated would run into `before`
65+
const end = directive && !directive[0].endsWith(";") ? ";" : "";
66+
// no newline after `before`: one would shift every line below it out
67+
// of the source map; a preparsed ast would be parsed instead of this
68+
return [
69+
`${code.slice(0, at)}${end}${before}${code.slice(at)}\n${after}`,
70+
sourceMap,
71+
undefined
72+
];
73+
}
74+
return result;
7575
}
76-
return result;
77-
}
78-
);
79-
});
80-
};
76+
);
77+
});
78+
}
79+
}
8180

8281
/** @type {import("../../").Configuration} */
8382
module.exports = {
84-
plugins: [addImports]
83+
plugins: [
84+
new AddImportsPlugin([
85+
[
86+
/legacy-lib\.js$/,
87+
{
88+
// the polyfill for its side effects, `$` as a binding the script reads,
89+
// and a wrapper so its top-level `this` is the global object
90+
before:
91+
'require("./polyfill.js");var $ = require("./jquery.js");(function () {',
92+
after: "}).call(globalThis);"
93+
}
94+
]
95+
])
96+
]
8597
};
8698
```
8799

‎examples/add-imports/webpack.config.js‎

Lines changed: 59 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -10,59 +10,71 @@ const PLUGIN_NAME = "AddImportsPlugin";
1010
// the module sloppy, so the code goes after one.
1111
const DIRECTIVE = /^\s*(["'])use strict\1;?/;
1212

13-
/** @type {[RegExp, { before?: string, after?: string }][]} */
14-
const imports = [
15-
[
16-
/legacy-lib\.js$/,
17-
{
18-
// the polyfill for its side effects, `$` as a binding the script reads,
19-
// and a wrapper so its top-level `this` is the global object
20-
before:
21-
'require("./polyfill.js");var $ = require("./jquery.js");(function () {',
22-
after: "}).call(globalThis);"
23-
}
24-
]
25-
];
26-
2713
/**
2814
* Puts code around modules which read values they never import, before webpack
2915
* parses them, so the imports are read as the module's own.
30-
* @param {Compiler} compiler the compiler instance
31-
* @returns {void}
3216
*/
33-
const addImports = (compiler) => {
34-
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
35-
NormalModule.getCompilationHooks(compilation).processResult.tap(
36-
PLUGIN_NAME,
37-
(result, module) => {
38-
const [source, sourceMap] = result;
39-
for (const [test, { before = "", after = "" }] of imports) {
40-
// a global or sticky pattern keeps its lastIndex between calls,
41-
// which would skip the next module it is tested against
42-
test.lastIndex = 0;
43-
if (!module.resource || !test.test(module.resource)) continue;
44-
// a file no loader touched arrives as the buffer webpack read
45-
const code =
46-
typeof source === "string" ? source : source.toString("utf8");
47-
const directive = DIRECTIVE.exec(code);
48-
const at = directive ? directive[0].length : 0;
49-
// a directive its source left unterminated would run into `before`
50-
const end = directive && !directive[0].endsWith(";") ? ";" : "";
51-
// no newline after `before`: one would shift every line below it out
52-
// of the source map; a preparsed ast would be parsed instead of this
53-
return [
54-
`${code.slice(0, at)}${end}${before}${code.slice(at)}\n${after}`,
55-
sourceMap,
56-
undefined
57-
];
17+
class AddImportsPlugin {
18+
/**
19+
* Creates an instance of AddImportsPlugin.
20+
* @param {[RegExp, { before?: string, after?: string }][]} imports pairs of a resource condition and the code to put around it
21+
*/
22+
constructor(imports) {
23+
this.imports = imports;
24+
}
25+
26+
/**
27+
* Applies the plugin by registering its hooks on the compiler.
28+
* @param {Compiler} compiler the compiler instance
29+
* @returns {void}
30+
*/
31+
apply(compiler) {
32+
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
33+
NormalModule.getCompilationHooks(compilation).processResult.tap(
34+
PLUGIN_NAME,
35+
(result, module) => {
36+
const [source, sourceMap] = result;
37+
for (const [test, { before = "", after = "" }] of this.imports) {
38+
// a global or sticky pattern keeps its lastIndex between calls,
39+
// which would skip the next module it is tested against
40+
test.lastIndex = 0;
41+
if (!module.resource || !test.test(module.resource)) continue;
42+
// a file no loader touched arrives as the buffer webpack read
43+
const code =
44+
typeof source === "string" ? source : source.toString("utf8");
45+
const directive = DIRECTIVE.exec(code);
46+
const at = directive ? directive[0].length : 0;
47+
// a directive its source left unterminated would run into `before`
48+
const end = directive && !directive[0].endsWith(";") ? ";" : "";
49+
// no newline after `before`: one would shift every line below it out
50+
// of the source map; a preparsed ast would be parsed instead of this
51+
return [
52+
`${code.slice(0, at)}${end}${before}${code.slice(at)}\n${after}`,
53+
sourceMap,
54+
undefined
55+
];
56+
}
57+
return result;
5858
}
59-
return result;
60-
}
61-
);
62-
});
63-
};
59+
);
60+
});
61+
}
62+
}
6463

6564
/** @type {import("../../").Configuration} */
6665
module.exports = {
67-
plugins: [addImports]
66+
plugins: [
67+
new AddImportsPlugin([
68+
[
69+
/legacy-lib\.js$/,
70+
{
71+
// the polyfill for its side effects, `$` as a binding the script reads,
72+
// and a wrapper so its top-level `this` is the global object
73+
before:
74+
'require("./polyfill.js");var $ = require("./jquery.js");(function () {',
75+
after: "}).call(globalThis);"
76+
}
77+
]
78+
])
79+
]
6880
};

0 commit comments

Comments
 (0)