I am trying to require a module in a file that would be used only if the module is actually available. So the module is totally optional. This code will be distributed as part of a 3rd party library. The issue is that any user using webpack will see their build fail if I use import
, so I ended up using:
let webrtc = {};
try {
webrtc = require('my-optional-module');
} catch (err) {}
But even with this code, they will get a warning on projects that don't need this optional module:
[WEB] WARNING in ./node_modules/xxx
[WEB] Module not found: Error: Can't resolve 'my-optional-module' in '/Users/xxx/node_modules/xxx'
Edit: Using the answer below
let webrtc = {};
if(require.resolve('my-optional-module')) {
webrtc = require('my-optional-module');
}
But I get this warning:
Critical dependency: the request of a dependency is an expression
And this error:
Module not found: Error: Can't resolve 'my-optional-module' in xxx
Edit2:
Based on webpack instruction to do dynamic imports, I also tried:
var webrtc = {};
require.ensure(['my-optional-module'], function (require) {
return webrtc = require('my-optional-module');
});
But I still get:
Module not found: Error: Can't resolve 'my-optional-module' in xxx
To solve the "ReferenceError require is not defined" error, remove the type property if it's set to module in your package. json file and rename any files that have a . mjs extension to have a . js extension.
Cases where it is necessary to use both “require” and “import” in a single file, are quite rare and it is generally not recommended and considered not a good practice. However, sometimes it is the easiest way for us to solve a problem. There are always trade-offs and the decision is up to you.
One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .
If the given module is not a core module, Node. js will then begin to search for a directory named, "node_modules". It will start in the current directory (relative to the currently-executing Javascript file in Node) and then work its way up the folder hierarchy, checking each level for a node_modules folder.
It seems like this is a common issue in webpack. According to the configuration docs, you can use the flag module: { exprContextCritical: false }
in your webpack.config.js
to suppress this warning globally across your project, though the flag is considered deprecated and you may find more highly recommended solutions in the issue I linked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With