Navela
Navela

Reputation: 1983

Using css modules how do I define a global class

I am using css modules, however a library I use in a component to append tweets with JavaScript adds some elements to my component in the following structure:

<div class='user'></div>
<div class='tweet'></div>

I want to now style these elements in my css module for the component, as follows:

MyComponent.css

.user {
 /* styles */
}

.tweet {
 /* styles */
}

However of course now my .user class changes to .MyComponent__user___HZWfM due to the hash naming in the webpack loader.

How can I set a global style in my css module?

Upvotes: 13

Views: 31097

Answers (3)

GMKHussain
GMKHussain

Reputation: 4661

Can use module class with static class with this way.

myStyle.module.css

.moduleClass_g1m59k:global(.StaticClass) {
    background-color: orange;
}

Output will generate like this

.moduleClass_g1m59k.StaticClass {
    background-color: orange;
}

Upvotes: 2

svnm
svnm

Reputation: 24308

According to the css modules docs, :global switches to the global scope for the current selector. e.g. :global(.example-classname)

So this should work:

:global(.tweet) {
    text-align: left;
}
:global(.user) {
    text-align: left;
}

Or define a global block

:global {
    .tweet {
        text-align: left;
    }
    .user {
        text-align: left;
    }   
}

Upvotes: 34

Anthony Cregan
Anthony Cregan

Reputation: 983

Many people have struggled with this and there doesn't seem to be any one agreed upon solution. The one I have settled with involves some tweaking of your bundler and specifically addresses the need to import libraries as-is without having to wrap them or edit them manually.

In my webpack config I have set it to scan all files ending css except those within the 'node_modules' and 'src/static' folders. I import my libraries from here and they dont suffer the classname transforms so I am free to use regular classnames for global css and the className={styles.element} convention as usual for modular css (which will compile down to .component_element__1a2b3 or something similar).

Here is an example of a working production webpack config with this solution: http://pastebin.com/w56FeDQA

Upvotes: -1

Related Questions