Using css-loader inline with Webpack + React

独自空忆成欢 提交于 2019-12-08 19:42:01

问题


I'm building my React app with Webpack, and css-loader w/modules. I love it. Most of my stylesheets are very small, though, and I'd like to inline them within the same JSX file as my markup and JavaScript.

The CSS loader I'm using right now looks like this:

{ test: /\.(css)$/i, 
  loader: ExtractTextPlugin.extract("style-loader", "css-loader?modules") }

In my JSX, I import my separate CSS files like this:

import classNames from 'dashboard.css';
... 
<div className={classNames.foo}></div>;

This is then compiled and translated into something like:

<div class="xs323dsw4sdsw_"></div>

But what I'd like to do is something more like below, while still preserving the localized modules that css-loader gives me:

var classNames = cssLoader`
    .foo { color: blue; }
    .bar { color: red; }
`;

... 
<div className={classNames.foo}></div>;

Is this possible? How can I do this without having to actually require / import a separate file?


回答1:


I believe your issue is that you your current webpack configuration uses CSS Modules. CSS Modules automatically rename your CSS Classes to avoid global class name collisions.

The fix:

// remove 'modules' from the end of your css-loader argument

{ test: /\.(css)$/i, 
  loader: ExtractTextPlugin.extract("style-loader", "css-loader?modules") }

// like so

{ test: /\.(css)$/i, 
  loader: ExtractTextPlugin.extract("style-loader", "css-loader") }

Now your class names will be preserved. Although, I'm not sure why you want to do this. Do you care to share why?



来源:https://stackoverflow.com/questions/32766857/using-css-loader-inline-with-webpack-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!