1

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.

1
  • how about __webpack_modules__.hasOwnProperty(require.resolveWeak('image/exploration/' + imageId + '.png')) That way you don't have an exception and can still do a valid test. Commented Sep 11, 2017 at 10:04

3 Answers 3

4

I know the question states

I want to avoid the try/catch solution if possible.

However, if someone comes by here trying to get webpack not to crash while testing if module exists, here is what works:

// try if module exists
try {
   var module = require('../path/to/module');
}
// fallback if does not exists
catch(err) {
   var module = require('../path/to/fallback/module');
}

You will still get an error printed in the console, but webpack won't crash the application and correctly fallback to module provided in the catch{};

Sign up to request clarification or add additional context in comments.

3 Comments

My main problem with the try/catch approach is performance. I'm doing it with try/catch at the moment but would like to use something else if possible.
Yeah I was pulling my hairs to find a solution to this. No matter what I would try, it was crashing the app :/ For now, this is what I use as well. I just post it to help someone that would come across this thread as a fallback until someone comes with a best solution.
Also note that this will produce a warning in a build log
2
+50

what you did is the way but it only checks if that module was already loaded, you need to turn it into an async function if you want to check if that module is available.

have a look here: https://github.com/webpack/webpack/issues/526

you can write a function to simplyfy everything:

function moduleExists(moduleId) {

  return new Promise((resolve, reject) => {
    // check if that module was already loaded
    if(__webpack_modules__[require.resolveWeak(moduleId)]) {
      return resolve();
    }

    return import(moduleId)
      .then(() => resolve(), () => reject())
    ;
  });
}

moduleExists('foobaz' /* take care of absolute paths */ )
  .then(() => alert('yes'))
  .catch(() => alert('noope'))
;

const exists = await moduleExists('bar');

if(exists) { /* do stuff */ }

1 Comment

Well, you are still catching an exception but without using try/catch. I want to eliminate throwing an exception in the first case but after checking this multiple times I think it's next to impossible.
1
import(/* webpackIgnore: true */ 'ignored-module.js');

https://webpack.js.org/api/module-methods/#magic-comments

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.