Webpack 动态需要在 require 语句中使用加载器 [英] Webpack dynamic require with loaders in require statement
问题描述
是否可以在 require 语句中使用带有显式加载器的动态 require
和 require.context
?我希望能够做这样的事情,但它对我不起作用:
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
当我尝试这个时,我得到一个找不到模块"的错误,这使得 webpack 似乎将字符串的 my-loader!
部分视为文件路径的开始,但是我希望 my-loader!
被识别为加载器,如下所述:https://webpack.github.io/docs/using-loaders.html#loaders-in-require
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
推荐答案
加载器在编译时只运行一次,这意味着在你的 require.context
被编译后,它只是纯 Javascript.你可以这样写:
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);
require.context
返回的函数在运行时被评估.
The function returned by require.context
is evaluated at run-time.
这篇关于Webpack 动态需要在 require 语句中使用加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!