Skip to content

Commit 9ab5580

Browse files
docs(examples): add an example that adds exports to a module that has none (#21947)
* docs(examples): show how to add exports to a module that has none A legacy script, a vendored file, a bundle never written as a module: the exports are one appended line, and webpack parses them as the module's own, so they take part in tree shaking, mangling, const inlining and scope hoisting. No loader is involved — `NormalModule`'s `processResult` hook hands a plugin what the loaders produced and takes back a replacement. Both formats are shown: `module.exports =` for a script, `export { … }` for a module, the latter being what makes the file one. * docs(examples): reset the match pattern and scope the optimization claim A configured pattern with the `g` or `y` flag keeps its `lastIndex` between calls, so the next module tested against it is skipped; reset it first. The prose claimed both appended forms are optimized like a written `export`. Only the ES module one is: the example's own output shows `legacy-global.js` keeping runtime-defined exports, as any module that assigns its whole exports object does. Say which form gets what, and why to prefer `export`.
1 parent 9683e21 commit 9ab5580

8 files changed

Lines changed: 425 additions & 0 deletions

File tree

‎examples/add-exports/README.md‎

Lines changed: 287 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,287 @@
1+
# Adding exports to a module
2+
3+
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.
4+
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.
6+
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.
8+
9+
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.
10+
11+
# internals/add-exports-plugin.js
12+
13+
```javascript
14+
"use strict";
15+
16+
const { NormalModule } = require("../../../");
17+
18+
/** @import { Compiler } from "webpack" */
19+
20+
const PLUGIN_NAME = "AddExportsPlugin";
21+
22+
/**
23+
* Appends exports to modules which have none, before webpack parses them, so
24+
* the exports are read as the module's own.
25+
*/
26+
class AddExportsPlugin {
27+
/**
28+
* Creates an instance of AddExportsPlugin.
29+
* @param {[RegExp, string][]} exports pairs of a resource condition and the code to append
30+
*/
31+
constructor(exports) {
32+
this.exports = exports;
33+
}
34+
35+
/**
36+
* Applies the plugin by registering its hooks on the compiler.
37+
* @param {Compiler} compiler the compiler instance
38+
* @returns {void}
39+
*/
40+
apply(compiler) {
41+
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
42+
NormalModule.getCompilationHooks(compilation).processResult.tap(
43+
PLUGIN_NAME,
44+
(result, module) => {
45+
const [source, sourceMap] = result;
46+
for (const [test, code] of this.exports) {
47+
// a global or sticky pattern keeps its lastIndex between calls,
48+
// which would skip the next module it is tested against
49+
test.lastIndex = 0;
50+
if (!module.resource || !test.test(module.resource)) continue;
51+
// appending moves nothing before it, so the source map still fits;
52+
// a preparsed ast would be parsed instead of the appended code
53+
return [`${source}\n${code}`, sourceMap, undefined];
54+
}
55+
return result;
56+
}
57+
);
58+
});
59+
}
60+
}
61+
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} */
73+
module.exports = {
74+
plugins: [
75+
new AddExportsPlugin([
76+
// a script, so CommonJs exports
77+
[/legacy-global\.js$/, "module.exports = Legacy;"],
78+
// `export` makes the module an ES module, as it would in the source
79+
[/math\.js$/, "export { add, PI };"]
80+
])
81+
]
82+
};
83+
```
84+
85+
# example.js
86+
87+
```javascript
88+
import Legacy from "./legacy-global";
89+
import { add, PI } from "./math";
90+
91+
console.log(new Legacy().version, add(PI, 1));
92+
```
93+
94+
# legacy-global.js
95+
96+
```javascript
97+
// A legacy script — it defines a constructor and exports nothing.
98+
function Legacy() {
99+
this.version = "1.0.0";
100+
}
101+
```
102+
103+
# math.js
104+
105+
```javascript
106+
// A vendored file — it defines values and exports nothing.
107+
const PI = 3.14;
108+
109+
function add(first, second) {
110+
return first + second;
111+
}
112+
```
113+
114+
# dist/output.js
115+
116+
```javascript
117+
/******/ (() => { // webpackBootstrap
118+
/******/ var __webpack_modules__ = ([
119+
/* 0 */,
120+
/* 1 */
121+
/*!**************************!*\
122+
!*** ./legacy-global.js ***!
123+
\**************************/
124+
/*! unknown exports (runtime-defined) */
125+
/*! runtime requirements: module */
126+
/*! CommonJS bailout: module.exports is used directly at 6:0-14 */
127+
/***/ ((module) => {
128+
129+
// A legacy script — it defines a constructor and exports nothing.
130+
function Legacy() {
131+
this.version = "1.0.0";
132+
}
133+
134+
module.exports = Legacy;
135+
136+
/***/ }),
137+
/* 2 */
138+
/*!*****************!*\
139+
!*** ./math.js ***!
140+
\*****************/
141+
/*! namespace exports */
142+
/*! export PI [provided] [no usage info] [missing usage info prevents renaming] */
143+
/*! export add [provided] [no usage info] [missing usage info prevents renaming] */
144+
/*! other exports [not provided] [no usage info] */
145+
/*! runtime requirements: __webpack_require__.r, __webpack_exports__, __webpack_require__.d, __webpack_require__.* */
146+
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
147+
148+
"use strict";
149+
__webpack_require__.r(__webpack_exports__);
150+
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
151+
/* harmony export */ PI: () => (/* binding */ PI),
152+
/* harmony export */ add: () => (/* binding */ add)
153+
/* harmony export */ });
154+
// A vendored file — it defines values and exports nothing.
155+
const PI = 3.14;
156+
157+
function add(first, second) {
158+
return first + second;
159+
}
160+
161+
162+
163+
/***/ })
164+
/******/ ]);
165+
```
166+
167+
<details><summary><code>/* webpack runtime code */</code></summary>
168+
169+
``` js
170+
/************************************************************************/
171+
/******/ // The module cache
172+
/******/ const __webpack_module_cache__ = {};
173+
/******/
174+
/******/ // The require function
175+
/******/ function __webpack_require__(moduleId) {
176+
/******/ // Check if module is in cache
177+
/******/ const cachedModule = __webpack_module_cache__[moduleId];
178+
/******/ if (cachedModule !== undefined) {
179+
/******/ return cachedModule.exports;
180+
/******/ }
181+
/******/ // Create a new module (and put it into the cache)
182+
/******/ const module = __webpack_module_cache__[moduleId] = {
183+
/******/ // no module.id needed
184+
/******/ // no module.loaded needed
185+
/******/ exports: {}
186+
/******/ };
187+
/******/
188+
/******/ // Execute the module function
189+
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
190+
/******/
191+
/******/ // Return the exports of the module
192+
/******/ return module.exports;
193+
/******/ }
194+
/******/
195+
/************************************************************************/
196+
/******/ /* webpack/runtime/compat get default export */
197+
/******/ // getDefaultExport function for compatibility with non-harmony modules
198+
/******/ __webpack_require__.n = (module) => {
199+
/******/ const getter = module && module.__esModule ?
200+
/******/ () => (module['default']) :
201+
/******/ () => (module);
202+
/******/ __webpack_require__.d(getter, { a: getter });
203+
/******/ return getter;
204+
/******/ };
205+
/******/
206+
/******/ /* webpack/runtime/define property getters */
207+
/******/ // define getter/value functions for harmony exports
208+
/******/ __webpack_require__.d = (exports, definition) => {
209+
/******/ for(var key in definition) {
210+
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
211+
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
212+
/******/ }
213+
/******/ }
214+
/******/ };
215+
/******/
216+
/******/ /* webpack/runtime/hasOwnProperty shorthand */
217+
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop));
218+
/******/
219+
/******/ /* webpack/runtime/make namespace object */
220+
/******/ // define __esModule on exports
221+
/******/ __webpack_require__.r = (exports) => {
222+
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
223+
/******/ Object.defineProperty(exports, '__esModule', { value: true });
224+
/******/ };
225+
/******/
226+
/************************************************************************/
227+
```
228+
229+
</details>
230+
231+
``` js
232+
let __webpack_exports__ = {};
233+
// This entry needs to be wrapped in an IIFE because it needs to be in strict mode.
234+
(() => {
235+
"use strict";
236+
/*!********************!*\
237+
!*** ./example.js ***!
238+
\********************/
239+
/*! namespace exports */
240+
/*! exports [not provided] [no usage info] */
241+
/*! runtime requirements: __webpack_require__, __webpack_require__.n, __webpack_require__.r, __webpack_exports__, __webpack_require__.* */
242+
__webpack_require__.r(__webpack_exports__);
243+
/* harmony import */ var _legacy_global__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./legacy-global */ 1);
244+
/* harmony import */ var _legacy_global__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_legacy_global__WEBPACK_IMPORTED_MODULE_0__);
245+
/* harmony import */ var _math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./math */ 2);
246+
247+
248+
249+
console.log(new (_legacy_global__WEBPACK_IMPORTED_MODULE_0___default())().version, (0,_math__WEBPACK_IMPORTED_MODULE_1__.add)(_math__WEBPACK_IMPORTED_MODULE_1__.PI, 1));
250+
251+
})();
252+
253+
/******/ })()
254+
;
255+
```
256+
257+
# Info
258+
259+
## Unoptimized
260+
261+
```
262+
asset output.js 4.85 KiB [emitted] (name: main)
263+
chunk (runtime: main) output.js (main) 417 bytes (javascript) 883 bytes (runtime) [entry] [rendered]
264+
> ./example.js main
265+
runtime modules 883 bytes 4 modules
266+
dependent modules 297 bytes [dependent] 2 modules
267+
./example.js 120 bytes [built] [code generated]
268+
[no exports]
269+
[used exports unknown]
270+
entry ./example.js main
271+
webpack X.X.X compiled successfully
272+
```
273+
274+
## Production mode
275+
276+
```
277+
asset output.js 514 bytes [emitted] [minimized] (name: main)
278+
chunk (runtime: main) output.js (main) 417 bytes (javascript) 672 bytes (runtime) [entry] [rendered]
279+
> ./example.js main
280+
runtime modules 672 bytes 3 modules
281+
dependent modules 141 bytes [dependent] 1 module
282+
./example.js + 1 modules 276 bytes [built] [code generated]
283+
[no exports]
284+
[no exports used]
285+
entry ./example.js main
286+
webpack X.X.X compiled successfully
287+
```

‎examples/add-exports/build.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
require("../build-common");

‎examples/add-exports/example.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import Legacy from "./legacy-global";
2+
import { add, PI } from "./math";
3+
4+
console.log(new Legacy().version, add(PI, 1));
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"use strict";
2+
3+
const { NormalModule } = require("../../../");
4+
5+
/** @import { Compiler } from "webpack" */
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+
module.exports = AddExportsPlugin;
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// A legacy script — it defines a constructor and exports nothing.
2+
function Legacy() {
3+
this.version = "1.0.0";
4+
}

‎examples/add-exports/math.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// A vendored file — it defines values and exports nothing.
2+
const PI = 3.14;
3+
4+
function add(first, second) {
5+
return first + second;
6+
}

0 commit comments

Comments
 (0)