【问题标题】:Injecting css file into head of html file generated using HtmlWebpackPlugin将css文件注入使用HtmlWebpackPlugin生成的html文件的头部
【发布时间】:2016-11-10 19:49:32
【问题描述】:

当 webpack 运行 babel-loader 时,我已将 babel-css-in-js plugin 配置为将 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

【问题讨论】:

  • 你可以看看或者只是使用魅力github.com/threepointone/glamor
  • @skav 魅力对我的内联样式有什么影响,呈现为style tagseperate file?它会自动注入文件还是需要我使用ExtractTextPlugin
  • 我使用react-helmetlink 注入头部。正在寻找更好的解决方案
  • 魅力在当前页面头部创建样式标签
  • @skav,我会尝试,似乎也支持服务器端渲染。和khan academy/aphrodite有什么区别

标签: javascript css webpack babeljs html-webpack-plugin


【解决方案1】:

我已经使用react-helmet 将外部样式表注入到生成的html 页面中。首先,我从webpack.config.js 中删除了css-loader,并从我的模块中删除了import ./bundle.css。我编辑了我的.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>);
}

看看.babelrcindex.js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多