0

I have a main CSS file style.styl, with the container:

.container
  // ...

I have another CSS file components.styl for some React components, and these must be inside the container

.container
  .componentA
    // ...
  .componentB
    // ...

And then after built by Webpack and CSS module with the following configuration:

{
  loader: require.resolve('css-loader'),
  options: {
    importLoaders: 1,
    modules: {
      localIdentName: '[name]__[local]__[contenthash:5]',
    },
  },
},

the .container in style.styl will be compiled to style__container__8cc45

the .container in components.styl will compiled to components__container__45aeb

Now how can I identify the container to the same name with [contenthash:5]

Thank you very much

  • I don't understand what are you trying to do. The main idea of css modules is to have unique separate name of class for module, so you do not need nesting of css rules. If you need it explicitly, do not do it in 2 files, put all your code of these 2 modules in single (css module) file. – lavor Nov 12 '19 at 09:46
  • @lavor, because I want the components must be inside the `container`. I add some reset style for the `container`, such as `container.*`. – user2235510 Nov 12 '19 at 10:10
  • These components are programmed by other engineers, so I want to apply the reset styles for their components (and they must be in the `container` scope) – user2235510 Nov 12 '19 at 10:15
  • Now I understand the problem. I think it is not possible to reference css module from another. See this answer: https://stackoverflow.com/questions/42587507/css-modules-referencing-classes-from-other-modules#answer-42588939 – lavor Nov 12 '19 at 12:52

1 Answers1

0

Thanks, @lavor

I found a solution to the problem (maybe not elegant)

// ...
loader: require.resolve('css-loader'),
options: {
  importLoaders: 1,
  modules: {
    calIdentName: '[local]__[contenthash:5]',
    getLocalIdent: (loaderContext, localIdentName, localName, options) => {
      if (!options.context) {
        options.context = loaderContext.rootContext;
      }

      let request = null;
      if (localName === 'container') {
        // do not change the value of `request` when localName is 'container'
        request = 'src/assets/css/style.styl';
      } else {
        request = path
            .relative(options.context, loaderContext.resourcePath)
            .replace(/\\/g, '/');
      }

      options.content = `${options.hashPrefix + request}+${localName}`;
      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');
    },
  },
},
// ...