Search code examples
javascriptcsswebpackbabeljshtml-webpack-plugin

Injecting css file into head of html file generated using HtmlWebpackPlugin


I have configured the babel-css-in-js plugin to build a css file into ./app/bundle.css when webpack runs the babel-loader. I need to inject this file into an HTML file generated by html-webpack-plugin. I have tried loading it through the css-loader like:

import './bundle.css';

const styles = cssInJs({
  red: {
    color: 'white',
    backgroundColor: 'red',
  },
});

const redClass = cx(styles.red);

function HelloWorld() {
  return (<h2 className={redClass}><LoremIpsum /></h2>);
}

but I get the error:

client?cb1f:75 ENOTSUP: operation not supported on socket,  
uv_interface_addresses
 @ ./app/index.js 17:0-23

 ./bundle.css not found

This is my .babelrc:

["css-in-js", {
 "vendorPrefixes":true,
 "mediaMap":{
   "phone": "media only screen and (max-width: 768px)",
   "tablet":"media only screen and (max-width: 992px)",
   "desktop":"media only screen and (max-width: 1200px)"
 },
 "identifier": "cssInJs",
 "transformOptions":{
 "presets":["env"]
 },
   "bundleFile": "./app/bundle.css"
 }
]

The html-webpack-plugin uses the html-webpack-template for its configuration like this:

new HtmlWebpackPlugin({
  inject: false,
  mobile: true,
  appMountId: 'root',
  template,
}),

Are there any other mechanisms that I can use to inject the css file into the head of the generated template?

The source of the project is on github


Solution

  • I have injected the external stylesheet into the generated html page using react-helmet. First, I removed the css-loader from the webpack.config.js and the import ./bundle.css from my module. I edited my .babelrc to change the bundlePath of the css to the build directory.

    Then I added:

    import Helmet from 'react-helmet';
    
    const cssLink = {
      rel: 'stylesheet',
      type: 'text/css',
      href: './bundle.css',
    };
    

    I added the following to my root component:

     <Helmet link={[cssLink]} />
    

    The component now looks like:

    function HelloWorld() {
      return (<h2 className={redClass}>
        <Helmet link={[cssLink]} />
        <LoremIpsum />
      </h2>);
    }
    

    Take a look at the .babelrc and index.js