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

发布于 2025-01-09 15:09:46 字数 277 浏览 0 评论 0原文

我正在开发一个遗留项目(基于 jQuery)。通过简单地将样式标签附加到标题中,可以使用 Javascript 添加一些 CSS:

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

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

I am working on a legacy project (based on jQuery). Some CSS is added with Javascript by simply appending the style-tag to the header:

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

I cannot rewrite the code using CSS modules so I am wondering if there is a way to bundle this CSS that gets injected via Javascript using Webpack 5.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流年里的时光 2025-01-16 15:09:46

找到了一种使用 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 的更多有趣的背景信息在这里:什么是`require.context`?

Found a way to make it work using require.context.

The following line makes all js files inside a certain folder available as build dependencies:

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

And this actually uses them (the jQuery code is just there because this legacy project is using jQuery, the important part is 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
        }
    });
)};

More interesting background info regarding require.context here: What is `require.context`?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文