Skip to content

Commit 4fffab6

Browse files
authored
docs(externals): update externalsType.node-commonjs usage (#7460)
1 parent e20e4d4 commit 4fffab6

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/content/configuration/externals.mdx

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -632,6 +632,49 @@ jq('.my-element').animate(/* ... */);
632632
633633
Note that there will be an `import` statement in the output bundle.
634634
635+
This is useful when dependencies rely on Node.js built-in modules or require a CommonJS-style `require` function to preserve prototypes, which is necessary for functions like [`util.inherits`](https://nodejs.org/api/util.html#utilinheritsconstructor-superconstructor). Refer to [this issue](https://github.com/webpack/webpack.js.org/issues/7446) for more details.
636+
637+
For code that relies on prototype structures, like:
638+
639+
```js
640+
function ChunkStream() {
641+
Stream.call(this);
642+
}
643+
util.inherits(ChunkStream, Stream);
644+
```
645+
646+
You can use `node-commonjs` to ensure that the prototype chain is preserved:
647+
648+
```js
649+
const { builtinModules } = require('module');
650+
651+
module.exports = {
652+
experiments: { outputModule: true },
653+
externalsType: 'node-commonjs',
654+
externals: ({ request }, callback) => {
655+
if (/^node:/.test(request) || builtinModules.includes(request)) {
656+
return callback(null, 'node-commonjs ' + request);
657+
}
658+
callback();
659+
},
660+
};
661+
```
662+
663+
This produces something like:
664+
665+
```js
666+
import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "node:module";
667+
// ...
668+
/***/ 2613:
669+
/***/ ((module) => {
670+
671+
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream");
672+
673+
/***/ }),
674+
```
675+
676+
This setup keeps the prototype structure intact, resolving issues with Node.js built-ins.
677+
635678
### externalsType.promise
636679
637680
Specify the default type of externals as `'promise'`. Webpack will read the external as a global variable (similar to [`'var'`](#externalstypevar)) and `await` for it.

0 commit comments

Comments
 (0)