mjc1283
mjc1283

Reputation: 213

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

Upvotes: 17

Views: 6880

Answers (1)

matpie
matpie

Reputation: 17512

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.

Upvotes: 25

Related Questions