Skip to content

Commit c6d157f

Browse files
committed
A different approach to Webpack optional require
1 parent 10f13fa commit c6d157f

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

node_package/src/reactHydrateOrRender.ts

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,16 @@ const supportsReactCreateRoot = parseInt(ReactDOM.version.split('.')[0], 10) >=
1010
// eslint-disable-next-line @typescript-eslint/no-explicit-any
1111
let reactDomClient: any;
1212
if (supportsReactCreateRoot) {
13-
// eslint-disable-next-line camelcase
14-
if (__webpack_require__) {
15-
// we are in a Webpack environment (and in a node-modules directory of another project)
16-
// See https://webpack.js.org/guides/dependency-management/#context-module-api
17-
const reactDomContext = require.context('react-dom/', false, /^client\.js$/);
18-
reactDomClient = reactDomContext('react-dom/client.js');
19-
} else {
20-
// we want a dynamic require here so that webpack doesn't rewrite it
21-
const reactDomClientName = 'react-dom/client';
22-
// eslint-disable-next-line global-require,import/no-dynamic-require
23-
reactDomClient = require(reactDomClientName);
13+
// This will never throw an exception, but it's the way to tell Webpack the dependency is optional
14+
// https://github.com/webpack/webpack/issues/339#issuecomment-47739112
15+
// Unfortunately, it only converts the error to a warning.
16+
try {
17+
// eslint-disable-next-line global-require,import/no-unresolved
18+
reactDomClient = require('react-dom/client');
19+
} catch (e) {
20+
// We should never get here, but if we do, we'll just use the default ReactDOM
21+
// and live with the warning.
22+
reactDomClient = ReactDOM;
2423
}
2524
}
2625

0 commit comments

Comments
 (0)