将css文件注入HtmlWebpackPlugin生成的html文件的头部

Injecting css file into head of html file generated using HtmlWebpackPlugin

本文关键字:文件 头部 html HtmlWebpackPlugin css 注入      更新时间:2023-09-26

我已经配置了babel-css-in-js插件,当webpack运行babel-loader时,构建一个css文件到./app/bundle.css。我需要将此文件注入到html-webpack-plugin生成的HTML文件中。我试过通过css-loader加载它,如:

import './bundle.css';
const styles = cssInJs({
  red: {
    color: 'white',
    backgroundColor: 'red',
  },
});
const redClass = cx(styles.red);
function HelloWorld() {
  return (<h2 className={redClass}><LoremIpsum /></h2>);
}

但是我得到错误:

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

我的.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"
 }
]

html-webpack-plugin使用html-webpack-template作为它的配置,像这样:

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

是否有任何其他机制,我可以使用注入css file到生成的模板的头部?

项目的源代码在github

我已经使用react-helmet将外部样式表注入生成的html页面。首先,我从webpack.config.jsimport ./bundle.css模块中删除了css-loader。我编辑了我的.babelrc,将cssbundlePath更改为build目录。

然后我加上:

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

我在根组件中添加了以下内容:

 <Helmet link={[cssLink]} />

组件现在看起来像:

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

看一下。babelrc和index.js