Dynamic file path required with webpack?

This works fine when I manually request a file using require , however the moment I use the same request, but change the string so that it breaks into variables that it fails.

This works great:

 module.exports = (function() { var $svg = require('svg-inline!../../assets/svgs/global/connected.svg'); console.log($svg); }()); 

However, if I did this:

 module.exports = (function() { var $path = '../../assets/svgs/global/'; var $svg = require('svg-inline!'+$path+'connected.svg'); console.log($svg); }()); 

It does not work and says inside the console:

Uncaught Error: Cannot find module "."

I think my question is why you cannot concatenate strings like I am here?

+6
source share
2 answers

I think you need to look into the webpack context . Basically, when you try to require something containing an expression, webpack will create a context. This expression will be considered a regular expression, and it does not work as you might expect.

+2
source

Try:

 require(`svg-inline!${$path}connected.svg`) 

and if you need more variable in the dynamic path try split:

 function getIcon(name) { const [category, filename] = name.split(":"); if (filename) { return require(`one_directory/icons/${category}/${filename}.svg`); } else { return require(`two_directory/icons/${name}.svg`); } } 
0
source

All Articles