简体   繁体   English

Webpack动态需要在require语句中使用加载器

[英]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? 是否可以在require语句中使用动态requirerequire.context以及显式加载器? 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! 当我尝试这个时,我得到一个'找不到模块'错误,使得看起来像webpack正在处理my-loader! part of the string as the start of a file path, but I want my-loader! 字符串的一部分作为文件路径的开头,但我想要my-loader! to be recognized as a loader, as described here: https://webpack.github.io/docs/using-loaders.html#loaders-in-require 被识别为加载器,如下所述: https//webpack.github.io/docs/using-loaders.html#loaders-in-require

Loaders are run only once at compile-time, which means after your require.context is compiled, it's just pure Javascript. require.context器在编译时只运行一次,这意味着在编译require.context之后,它只是纯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. require.context返回的函数在运行时进行评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM