Guide on sharing CSS via NPM

In an effort to modularize my extensive React application into reusable components that can be shared with other projects, I am looking to create a mini UI library consisting of generic components like Buttons, Headers, and Dropdowns. However, the challenge lies in managing the CSS since my current approach involves a single stylesheet for the entire app.

There are a couple of solutions I've come across:

  1. Include the CSS styles within the JS file of each component (CSS in JS).
  2. Use import or require statements to bring CSS files into the component's JS file and utilize webpack to bundle the CSS.

While these options have their benefits, they don't quite align with my preferences. Embedding the styles in the component feels cluttered and limits the flexibility of cascading styles. On the other hand, importing CSS files directly into JS just doesn't sit right with me as it blurs the line between JavaScript and CSS.

Are there any alternative methods for incorporating a traditional CSS file from an NPM module without resorting to copying and pasting from node_modules? I'm open to suggestions for a more seamless solution. :)

Answer №1

Big shoutout to @EmileBergeron for pointing me towards the PostCSS import plugin. This nifty tool can track down and embed stylesheets from both node_modules and your own code base.

My new workflow looks something like this:

  1. npm install my-ui-library
  2. Bring in the React components you need by adding
    import { Button } from 'my-ui-library'
    to your JS files
  3. Include the corresponding CSS files by using
    @import 'my-ui-library/Button.css'
    in your CSS files

This method keeps CSS with CSS and JS with JS, creating a more seamless integration. While it may be tempting to consolidate all styles into one sheet instead of per-component, that decision can wait for another day.

Adding PostCSS to the build pipeline for inline processing has been surprisingly straightforward during testing phases.

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 is the method for executing the command "npm test" through the WebStorm file watcher feature?

How can I set up npm test to automatically run whenever a file changes in Webstorm? I'm aware of creating a run configuration from NPM but prefer not having to trigger it manually each time. ...

Adjust the appearance attribute of FormField within the designated theme

Currently, I am collaborating within an NX Monorepo and utilizing a shared ui-components library that extends the capabilities of Angular Material Components. Despite using different themes for various applications, I am aiming to incorporate appearance=&a ...

What steps do I need to take to integrate FontAwesome with the vue-cli webpack-simple template?

First, I create a new project using vue-cli: vue init webpack-simple grid-prototype Next, I add FontAwesome to my project via npm: npm install --save fontawesome Once installed, I include it in my main.js file with the following code: import 'fon ...

What is the best way to align elements within a row/column layout in Angular Material when working with divs?

To set up two div blocks in a row, I'm utilizing the code below: <div layout="column" layout-gt-xs="row" layout-align="center center" id="row"> <div id="a">a</div> <div id="b">b</div> </div> The CSS for this ...

Struggling to Make Text Overlay Transparent and Slide Only to the Right

Can someone help me make my image have an opaque overlay with text that slides only right when hovered over? Currently, it's sliding both right and up. Any suggestions on how to fix this issue would be greatly appreciated. Thank you. html, body{ ...

Steps to finding the electron sha256 hash

I'm in the process of setting up electron through the cache. After some digging, I managed to find the SHA256 hash for electron version v22.0.0: 675dc6eec89d1ddd1fa1f035915944bbec766951c6cd149c5ddcc3056471a91d. Now, my goal is to upgrade to the lates ...

Kindly execute the command `npm cache clean` to clear the npm

Currently, I am attempting to install IPFS from this link using the command npm install ipfs --save. Unfortunately, I encountered the following error message: npm ERR! tar.unpack error reading /media/FLASH/Tech/IPFS/ipfs npm ERR! addLocal Could not insta ...

What is the best way to stream audio data stored as a Buffer from my API to my React frontend and play it back?

I've spent the last couple of days trying to figure out the best approach for sending the <Buffer ... > object generated by Google's Text-To-Speech service from my express-api to my React app. I've sifted through numerous opinionated r ...

Using React in Visual Studio without ASP.NET Core is a great way to build

Is it possible to run React applications in Visual Studio without ASP.NET Core? By default, Visual Studio sets up React applications within an ASP.NET Core environment. However, I am interested in running a pure React application without the need for ASP. ...

javascript various backgrounds on click

I have implemented a list to allow users to select their top 3 choices, and I am using JavaScript to track these selections and change the background color accordingly. 1st selection -> Green background 2nd selection -> Yellow background 3rd sel ...

What could be causing the if statement to evaluate as false even though the div's style.display is set to 'block'?

Building a react application using createreactapp and encountering an issue with an if statement that checks the CSS display property of a div identified as step1: const step1 = document.getElementById("step-1") if (step1.style.display === 'blo ...

Trouble with Leafletjs Routing Machine collapse button loading issue

In my project, I am using django 1.10.5, booststrap 4.0, and LeafletJs 1.0.3 along with the routing machine plugin and geocoder. However, I have encountered an issue where the collapse button of the control panel for the routing machine does not appear (it ...

IE8 experiencing issues with colgroup tag

Having trouble styling a data table with alternating row colors. 1) Need help applying alternating row style without having to add classes to each individual TD? 2) Colgroup works in IE8 but having alignment issues for specific columns (cols=A&SI Cap ...

Minimize the gap between col-lg elements in responsive mode within Bootstrap

My website is built using Bootstrap 4 and the following is the HTML code: <div class="container"> <div class="row text-center "> <div class="col-lg-6">A</div> <div class="col-lg-6">B</div> </div> < ...

What are the recommended guidelines for utilizing the private keyword?

While reviewing our React codebase, I've noticed that almost every function within all components has the private keyword in front of it. Specifically, this pattern is present in class components, such as: private componentDidMount() { this.props.o ...

I am looking to transmit the text inputted into a modal using React.js to the Backend server

Working on the front-end of a web app with React.js to control home appliances. The goal is to send modal text to the backend without reloading the page. Encountering an issue where submitting the modal text causes a page reload, hindering console visibi ...

Support for a few breakpoints within Bootstrap

I am tasked with creating only 2 breakpoints for a specific application. These 2 breakpoints are <=768 for mobile and >=1280 for desktop. (No Tablet breakpoint) How do I adjust the $grid-breakpoints to accommodate this setup? I think it should be d ...

Utilizing CSS nth-child on dynamically generated HTML in Angular

Ensuring that the columns are floated to the left without large gaps between rows is my current challenge. Here's the HTML structure I'm working with: <div class="row hide-for-small"> <div ng-repeat="module in modules"> ...

Get the value of a CSS property in Python by parsing the rendered HTML

Currently, I am using Selenium and PhantomJS in conjunction with Python for the purpose of crawling rendered web pages. While it is a straightforward process to identify the presence of specific words within the HTML content (e.g. if "example" in html...), ...

``I am experiencing difficulties with utilizing a personalized color scheme in React JS with Material

I'm currently working on customizing the color palette for my project, but I am only able to modify the main attribute and not others. My development environment is JavaScript with MUI, not Typescript. import './App.css'; import {BrowserRout ...