Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using require('...') with a variable vs. using a string in webpack

I have a problem that doesn't make much sense to me.

I'm mapping an array of objects that have a "name" and a "href" property.

let appleIcons = _.map(appleIcons, appleIcon => {
  appleIcon.href = require(appleIcon.href);
  return appleIcon;
}); 

Inside of the loop I want to require the image but it throws an error ".*$:11 Uncaught Error: Cannot find module".

When I print the value of appleIcon.href and i try to put it directly into the require('') it works.

appleIcons = _.map(appleIcons, appleIcon => {
  appleIcon.href = require('./../../mobile-config/apple-icon-57x57.png');
  return appleIcon;
});

So can you explain me why the second example works and the first one throws an error? How do i put a variable inside of require('')?

Thanks!

like image 790
Kitze Avatar asked May 15 '16 17:05

Kitze


People also ask

Can you use require with Webpack?

Each time you use the AMD-style require([]) or require. ensure() webpack will see what you passed in there and go and create a bundle with every possible match. That works great if you pass in a single file, but when you use a variable, it might end up bundling your entire view folder.

What is Webpack_require?

Here, starts the function declaration of __webpack_require__ . It takes moduleId as a parameter and whenever this function is invoked when the cache is being checked if the module is already loaded or not. If yes then the module is returned from the cache else we load the module. . exports is not native module export .


2 Answers

Since Webpack is running in build-time, it can't figure out which modules to bundle when the name is a dynamic variable. You can give it hints by specifying part of the path (for example, if you know all the modules are in a single directory).

This answer can help: https://stackoverflow.com/a/33048000

(Also check require.context by Webpack. Another example is karma tests, here.)

Alternatively - if you know the filenames in advanced, it's better to add another build step to output them a strings to the file, that way Webpack can bundle them.

like image 100
lyosef Avatar answered Oct 24 '22 01:10

lyosef


Adding an empty string fixed the problem for me. So, below code should work:

let appleIcons = _.map(appleIcons, appleIcon => {
  appleIcon.href = require('' + appleIcon.href);
  return appleIcon;
});
like image 21
Deepak Avatar answered Oct 24 '22 01:10

Deepak