在没有 CSS 模块的情况下在 Webpack 5 中动态加载 CSS?

Dynamically loading CSS in Webpack 5 without CSS modules?

我正在处理遗留项目(基于 jQuery)。通过简单地将 style-tag 附加到 header 来添加一些 CSS Javascript:

$("head").append("<link href='" + path + "' rel='stylesheet' type='text/css' media='screen' />")

我无法使用 CSS 模块重写代码,所以我想知道是否有办法使用 Webpack 5 捆绑通过 Javascript 注入的 CSS。

找到了使用 require.context 使其工作的方法。

以下行使特定文件夹中的所有 js 文件都可用作构建依赖项:

var req_js = require.context("./components", true, /.js$/);

这实际上使用了它们(jQuery 代码就在那里,因为这个遗留项目正在使用 jQuery,重要的部分是 req_js(key)):

$.each(window.app.config.components, function(componentName) {

    req_js.keys().forEach(function(key){
        if (key.split('/')[1] === componentName) {
            req_js(key);  //this actually calls/uses these dependencies
        }
    });
)};

更多关于 require.context 的有趣背景信息,请点击此处: