简体   繁体   English

使用 CSS 模块和第三方包

[英]Using CSS Modules and 3rd party packages

Here is the relevant part of my webpack.config.js file:这是我的webpack.config.js文件的相关部分:

module: {
    loaders: [
        {
            test: /\.css$/,
            exclude: /node_modules/,
            loaders: [
                "style-loader?sourceMap",
                "css-loader?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]"
            ]
        },
        {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: "babel-loader"
        }
    ]
}

This works great when I'm writing my own css and using it with my React components.当我编写自己的 css 并将其与我的React组件一起使用时,这非常有用。 However, I recently tried using React Datepicker and it comes with its own css files to import into the component that uses React Datepicker.但是,我最近尝试使用React Datepicker ,它带有自己的 css 文件,可以导入到使用 React Datepicker 的组件中。

How can I modify my webpack.config.js file so that the React Datepicker css files that I import DON'T get transformed by CSS Modules with local class names?如何修改我的webpack.config.js文件,以便我导入的 React Datepicker css 文件不会被具有本地 class 名称的 CSS 模块转换? In order words, is it possible to configure webpack so that it imports 3rd party styles to the global scope and my own styles to a local scope?换句话说,是否可以配置 webpack 以便将第三方 styles 导入全局 scope 并将我自己的 styles 导入本地 scope?

Also, if I want to write my own custom styles that override the React Datepicker styles, how would I do it so that those styles are in global scope as well?另外,如果我想编写自己的自定义 styles 来覆盖 React Datepicker styles,我该怎么做才能使那些 styles 也位于全局 scope 中?

The problem with your setup is exclude: /node_modules/ . 您的设置问题是exclude: /node_modules/ Remove this line from your css loader setup, and your React-datepicker should work. 从您的css加载程序设置中删除此行,您的React-datepicker应该可以工作。

If you want to override the default style of a third-party component, you can 如果要覆盖第三方组件的默认样式,则可以

  1. Find out if the library support it by default, some provides themeing options 查看默认情况下库是否支持它,有些提供了主题选项
  2. or, you can always find out the CSS that s generated by the library, then override the rules with your own. 或者,您始终可以找到库生成的CSS,然后使用您自己的规则覆盖规则。

Edit : 编辑

In the case you have to import css explicitly, you can just create a new loader, like this: 如果你必须显式导入css,你可以创建一个新的加载器,如下所示:

{
  test: /\.css$/,
  exclude: /node_modules/,
  loader: 'style!css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
},
{
  test: /\.css$/,
  include: /node_modules/,
  loader: 'style!css'
}

Using:global(.classname) you can override the external classnames.使用:global(.classname) 你可以覆盖外部类名。

Even 3rd party library css can be override.甚至可以覆盖第 3 方库 css。

:global(.classname) {
  background-color: #fff;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM