Often I need to check if a dependency exists in webpack. For example, I have a bunch of ids like [0,1,3,4,5,6,7,8,...] and some of them have an image I should load while others don't.
How I check that an image should be loaded is by creating an array that contains the values that have an image and just do an array.contains when checking that the image should be loaded. Like [1,5,7,...].
This is starting to be quite problematic because I need to change this array every time I add or remove images.
Is there a way to check if the module I want to require exists or not?
As far as I see there was a way in Webpack 1 but that go closed.
https://github.com/webpack/webpack/issues/526
I found that it should still work like this according to the documentation (https://webpack.js.org/api/module-methods/#require-resolveweak) but I do get Error: Cannot find module.
This is what I'm doing exactly:
$scope.getExplorationImage = function (imageId) {
if(__webpack_modules__[require.resolveWeak('image/exploration/' + imageId + '.png')]) {
console.log("Image exists for: "+imageId)
return require('image/exploration/' + imageId + '.png');
} else {
console.log("Image doesn't exists: "+imageId)
}
};
I'm using Webpack 3.5.5. I want to avoid the try/catch solution if possible.
__webpack_modules__.hasOwnProperty(require.resolveWeak('image/exploration/' + imageId + '.png'))That way you don't have an exception and can still do a valid test.