使用css-loader内联Webpack + React [英] Using css-loader inline with Webpack + React

查看:751
本文介绍了使用css-loader内联Webpack + React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Webpack构建我的React应用程序,并使用css-loader w / modules。我喜欢它。我的大多数样式表是非常小的,但是,我想内联在同一个JSX文件中我的标记和JavaScript。

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.

CSS加载程序使用现在看起来像这样:

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

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

我的JSX,我 import 我的单独的CSS文件像这样:

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>

但是我想做的是更像下面的内容, css-loader 给我:

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>;

这可能吗?我怎么能这样做,而不必实际 require / import 一个单独的文件?

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

推荐答案

我相信你的问题是,你当前的webpack配置使用CSS模块。 CSS模块自动重命名您的CSS类,以避免全局类名冲突。

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.

修复:

// 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?

这篇关于使用css-loader内联Webpack + React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆