Search code examples
webpackwebpack-style-loader

Dynamically loading CSS in Webpack 5 without CSS modules?


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.


Solution

  • 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`?