Incorporating global stylesheets alongside CSS Modules

Currently, I am utilizing the react boilerplate for my project. This boilerplate makes use of CSS Modules and postCSS for styling, which I find to be quite beneficial. However, I also require some global CSS files for typography, base components, and more. What would be the most recommended approach for incorporating these global styles? I have considered using preCSS, but I am unsure about the setup process in webpack to import these global files into the main stylesheet. My background is more Gulp/Grunt based and I work with Sass, so I am relatively new to webpack. Any guidance in this regard would be highly appreciated.

Additionally, it would be advantageous if I could utilize the variables and mixins defined in these global files within the CSS module files. Is this even feasible or advisable? To facilitate this, I have installed react-css-modules so that I can make use of styleName for referring to the CSS Module file and className for accessing the global CSS classes.

I am aware of the

composes: class from '/path/to/file.css';
attribute, but I would prefer having specific global files where utility classes like clearfix and error classes are defined. By employing react-css-modules, the implementation might look something similar to the following:
<div className="clearfix" styleName="app-header">{...}</div>

However, I am uncertain if this is the correct approach. As I am contributing to an open-source project, I strive to adhere to best practices and ensure that the implementation is of the highest standard possible. I appreciate any advice provided on this matter! Thank you.

Answer №1

Using css-modules, you have access to the :global feature which allows you to import CSS files locally in your code but have them applied globally throughout the application.

Answer №2

When I encountered a challenge trying to use a third-party library that needed certain css files directly referenced in the js templates through class name strings, and css modules were not supported, I had to find a solution. Instead of altering the css files by adding a global modifier, which could lead to complications if they changed in the future, I discovered a mode setting in the css-loader that allowed me to preserve the original names for specific files.

Here's how it functions:

The mode setting in the css-loader, alongside other options, includes a function parameter. This function takes a resourcePath as input and returns either local, global, or pure values. Using 'global' retains the original names from the source file, while 'local' applies standard hashing. This feature proves useful for integrating third-party libraries that are incompatible with css modules.

To address this issue, I devised a simple function to inspect the resourcePath for modules requiring global retention. While effective, this approach does mean writing the function twice for development and production configurations.

Below is an example configuration for the development environment:

{
    loader: 'css-loader',
    options: {
        modules: {
            localIdentName: '[name]_[local]_[hash:base64:6]',
            exportLocalsConvention: 'camelCase',
            mode: (resourcePath) => {
                let globalStyles = ['module-to-stay-global-1', 'module-to-stay-global-2'];
                return globalStyles.some(globalFile => resourcePath.includes(globalFile)) ? 'global' : 'local'
            }
        },
    }
}

Detailed documentation on the mode function can be accessed at: https://github.com/webpack-contrib/css-loader#function-3

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What's the optimal method for displaying a component with an onClick event in React?

My Goal: I want to create a functionality where each time a user clicks on a button, a new component containing an image is rendered. The Issue: Currently, my setup involves the handleClick function toggling a state to true, which loads the component. How ...

Calculating the computed width based on flex-basis at 0% and the flex-grow factor: what's the deal

Below is an example of HTML with default flex properties being used: <div class="container"> <div class="box"> BOX 1</div> <div class="box"> BOX 2</div> <div class="box box2"> BOX 3 .</div> </div> The ...

Incorrect legend colors in Highcharts pie chart

[![enter image description here][1]][1] There seems to be an issue with the Pie-Chart where the Slice color and the Legend color do not match when the color is set using className. This problem does not occur with some other charts. If you look at the co ...

Ways to hide the value from being shown

I have integrated jscolor (from jscolor) to allow users to pick a color with an input field. However, I am facing issues in styling it as I'm unable to remove the hex value of the selected color and couldn't find any relevant documentation on av ...

Customize MUI datagrid by highlighting specific rows with bold text

In my React project, I have a simple MUI DataGrid that retrieves data from an API. The grid dynamically creates columns and rows based on the data, with each row specifying whether its content should be bold or not. My issue now is how to actually make th ...

Strange Behavior: Material-UI Dialog Closes Unexpectedly on iPhone due to Phantom topClick Events

I've been using the Material-UI Dialog element for quite some time now, and it has always functioned perfectly. However, I recently noticed an issue while testing in Chrome's device emulation mode. It seems that when the dialog or drawer is opene ...

The continuous loop caused by useEffect baffles me as I struggle to comprehend its workings entirely

I've encountered similar issues with infinite recursion in the past, but I'm struggling to pinpoint my mistake. Here are the crucial components of my function: At the top, I define these constants: const PREV_ICON = <span aria-hidden="t ...

What is the best way to incorporate a video into a ReactJs project?

Having some trouble with my video elements not displaying properly. Any help with my code would be greatly appreciated! This is the Video.js file: import React from "react"; import "./Video.css"; function Video() { return ( < ...

Updating state in React Textarea is not possible

I'm currently developing a ReactJs application. Within this project, I have implemented a Textarea that is linked to a state <Textarea className="c-input" tabIndex="7" minRows={4} ref="adMessage" onKeyPress={ console.log('keypress tex ...

Alert: Error encountered while attempting to locate the Angular Material core theme within Angular 3, Angular Material, and Angular Material Experimental

After successfully implementing a custom color palette with Material 3 and Angular Material Experimental, I am encountering a warning in the console stating "Could not find Angular Material core theme. Most Material components may not work as expected. For ...

Comparing Embedded and Linked JS/CSS

In my experience, I understand the advantages of using linked CSS over embedded and inline styles for better maintainability and modularity. However, I have come across information suggesting that in certain mobile web development applications, it may be m ...

What's the best way to adjust the alignment of these elements?

I'm having trouble aligning a material icon with text. Here's the HTML I'm currently using: <!DOCTYPE html> <body scroll="no" style="overflow: hidden"> <html> <head> <body> <link href=&apo ...

Is there a way to customize Material UI theme types and make adjustments to existing types using Typescript?

One way to customize the material ui theme is by extending its type and adding new properties, as shown here: For example, if we want to add an appDrawer property, it can be done like this: declare module '@material-ui/core/styles/createMuiTheme&apos ...

Unable to save images in API using POST method in React Native for Android

... encountering issues with uploading images using React Native and an API. The error message states that the image is not in the correct FormData format. ... ... Below is the code I have been using to upload the image to the API. I have tried using Form ...

Ways to extract subarray elements that meet a certain condition and break out of the loop

const winningTemplate = { firstRow: [0, 1, 2, 3, 4], secondRow: [5, 6, 7, 8, 9], thirdRow: [10, 11, 13, 14], fourthRow: [15, 16, 17, 18, 19], lastRow: [20, 21, 22, 23, 24], firstDiagonal: [0, 6, 18, 24], firstColumn: [0, 5, 10, ...

React Native Error - Node not found in an unrendered component

I'm fairly new to testing React and React Native apps, so I recently started setting up some tests in my React Native app using expo. I've installed jest, jest expo, and react-test-renderer for this purpose. I wanted to run a simple test, but I&a ...

Modify the card design when the screen is reduced in size and when the workspace is comprised of only two words

https://i.stack.imgur.com/jBqTE.png In my current project aimed at organizing tasks within companies, I am facing an issue with displaying a group of workspaces. The problem occurs when viewing the card changes its shape on a minimized screen, but only wh ...

What could be causing my div to overflow its parent div when the screen size is adjusted?

I've been developing my personal portfolio using only pure HTML and CSS, aiming to create a responsive site with media queries. The code below showcases two sections of my portfolio. The issue I'm facing is with the div class "worked-dash." When ...

React allows for items to be exchanged between two lists

I am currently working on a functionality that involves swapping items between two arrays. The user interacts with two lists in the UI by selecting items from the first list, which should then be removed from there and added to the second list where the se ...

Creating a vertical line in HTML: A step-by-step guide

What is the HTML code for creating a vertical line? ...