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

I have a problem that makes no sense to me.

I map an array of objects having the property "name" and "href".

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

Inside the loop, I want to request an image, but it throws an error ". * $: 11 Unused error: cannot find the module."

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

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

So can you explain to me why the second example works, and the first causes an error? How to put a variable inside require ('')?

Thanks!

+8
javascript webpack
source share
1 answer

Because Webpack works during build time, it cannot determine which modules to bind when the name is a dynamic variable. You can give him hints by indicating part of the path (for example, if you know that all modules are in the same directory).

This answer may help: stack overflow

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

Alternatively, if you know the file names in the extended one, it’s better to add another build step to output them to a file, so Webpack can link them.

+11
source share

All Articles