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
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 standardstyle-loader
andcss-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.
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:
Then, in your webpack configuration file (usually named webpack.config.js), you can set up rules to handle CSS files:
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:
When bundled with webpack, it will result in: