简体   繁体   English

如何在 css-modules 中实现 react-dates css?

[英]How to implement react-dates css in css-modules?

so react-dates css worked fine until i moved to css-modules.所以 react-dates css 工作正常,直到我搬到 css-modules。 i tried importing the css file from node modules in index.js files and in the head of the html file but none of them worked.我尝试从 index.js 文件中的节点模块和 html 文件的头部导入 css 文件,但它们都不起作用。 Any help or suggestion will be greatly appreciated.任何帮助或建议将不胜感激。

This is working perfectly for this problem这对这个问题非常有效

In webpack.config.js define a function which checks your file to decide if it's css module or global ;webpack.config.js定义一个函数来检查你的文件以确定它是css 模块还是global done using getLocalIdent option.使用 getLocalIdent 选项完成。

This is the method that I'm currently using in my setup.这是我目前在设置中使用的方法。

This also requires your files to have some naming convention, [name].module.css for css modules and [name].css for regular files.这也要求你的文件有一些命名约定,[name].module.css 用于 css 模块,[name].css 用于常规文件。 See example below:请参阅下面的示例:

// regex to test for modules, loaderUtils is part of webpack dependencies
const cssModuleRegex = new RegExp(/\.module\.(less|css)$/);
const loaderUtils = require("loader-utils");

// inside webpack rules
      {
        test: /\.(less|css)$/,
        use: [
          {
            loader: CssExtractPlugin.loader,
            options: { hot: is_dev, reloadAll: is_dev }
          },
          {
            loader: "css-loader",
            options: { 
                modules: { 
                    localIdentName: '[local]___[hash:base64:5]', 
                    getLocalIdent: getLocalIdent
                }
            }
          },
          "postcss-loader",
          "less-loader"
        ]
      }

// this is a copy of the default function, modified slightly to achieve our goal
function getLocalIdent(loaderContext, localIdentName, localName, options) {

    // return local name if it's a global css file
    if (!cssModuleRegex.test(loaderContext.resourcePath)) {
        return localName;
    }

    if (!options.context) {
      // eslint-disable-next-line no-param-reassign
      options.context = loaderContext.rootContext;
    }

    const request = path
      .relative(options.context, loaderContext.resourcePath)
      .replace(/\\/g, '/');

    // eslint-disable-next-line no-param-reassign
    options.content = `${options.hashPrefix + request}+${localName}`;

    // eslint-disable-next-line no-param-reassign
    localIdentName = localIdentName.replace(/\[local\]/gi, localName);

    const hash = loaderUtils.interpolateName(
      loaderContext,
      localIdentName,
      options
    );

    return hash
      .replace(new RegExp('[^a-zA-Z0-9\\-_\u00A0-\uFFFF]', 'g'), '-')
      .replace(/^((-?[0-9])|--)/, '_$1');
  }

Source: How to apply global styles with CSS modules in a react app?来源: 如何在 React 应用程序中使用 CSS 模块应用全局样式?

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

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