Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack dynamic require with loaders in require statement

Is it possible to use dynamic require and require.context with explicit loaders in the require statement? I'd like to be able to do something like this, but it's not working for me:

var req = require.context('../somedir', false, /\.js$/);
var imported = req('my-loader!' + someModulePath); // someModulePath defined above somewhere

When I try this, I get a 'module not found' error that makes it seem like webpack is treating the my-loader! part of the string as the start of a file path, but I want my-loader! to be recognized as a loader, as described here: https://webpack.github.io/docs/using-loaders.html#loaders-in-require

like image 372
mjc1283 Avatar asked Jul 15 '15 01:07

mjc1283


1 Answers

Loaders are run only once at compile-time, which means after your require.context is compiled, it's just pure Javascript. You can write it like this:

var req = require.context("my-loader!../somedir", false, /\.js$/);
var imported = req(someModulePath);

The function returned by require.context is evaluated at run-time.

like image 193
matpie Avatar answered Sep 19 '22 21:09

matpie