skip to Main Content

I was wondering if there was a webpack package that would inject the styles in the style attributes of corresponding tags.

Raw HTML:

<p class="par">
  <span class="blue"></span>
</p>

Raw CSS:

.par { margin-top: 10px; }
.par .blue { color: blue; }

Bundled:

<p style="margin-top: 10px;"><span style="color: blue;"></span></p>

Thanks!

2

Answers


  1. Webpack loader works at a file level and hence, you cannot achieve this with any kind of loader. The next best option is plugin, but unfortunately, no such Webpack plugin exists! (This is a pretty opinionated and a complex problem. You may be using plethora of CSS selectors like classNames, ids, attribute or sibling based selectors, pseudo classes, etc. may of which cannot be expressed with just inline style attribute).

    The closest thing you can get is embedding styles in the HTML document using <style /> tag with standard style-loader and css-loader.

    And, if your raw CSS is external to your code, you can use the CSS inline plugin which is well maintained.

    Finally, if you need to do this yourself, either you need to write your own plugin or you can post-process your generated HTML file. I will highly recommend using something like htmlparser2 to rewrite your HTML with inline styles.

    On a side note, it looks like you are trying to use Webpack for statically generated HTML pages (like a static site-builder) and not for bundling your SPA. In those cases, there are more better alternatives.

    Login or Signup to reply.
  2. Yes, there are several webpack loaders that can help you achieve this behavior. One of the popular ones is the style-loader.

    You can use it along with other loaders such as css-loader to process your CSS files and inject styles into your HTML.

    Here’s how you can set it up:

    First, install the necessary loaders using npm:

    npm install style-loader css-loader --save-dev
    

    Then, in your webpack configuration file (usually named webpack.config.js), you can set up rules to handle CSS files:

    module.exports = {
          module: {
            rules: [
              {
                test: /.css$/,
                use: ['style-loader', 'css-loader']
              }
            ]
          }
    };
    

    Now, when you import CSS files in your JavaScript files, webpack will process them using the css-loader and style-loader. The style-loader will inject the styles into the HTML using the style attributes of corresponding tags.
    For your example:

    <p class="par">
        <span class="blue"></span>
    
    .par { margin-top: 10px; }
    .par .blue { color: blue; }
    

    When bundled with webpack, it will result in:

    <p style="margin-top: 10px;"><span style="color: blue;"></span></p>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search