What could be causing the need to restart the server every time a style change is made?

I'm currently developing a NextJS application that utilizes PurgeCSS. It's quite frustrating because every time I tweak the classname of a component, I have to restart the server.

Here is a snippet from my postcss.config.js:

  plugins: [
    [
      '@fullhuman/postcss-purgecss',
      {
        content: [
          './src/pages/**/*.{js,jsx,ts,tsx}',
          './src/pages/*.{js,jsx,ts,tsx}',
          './src/components/**/*.{js,jsx,ts,tsx}',
          './src/containers/**/*.{js,jsx,ts,tsx}',
        ],
        defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [],
        safelist: ['html', 'body'],
        enableDevPurge: false,
      },
    ],
    'postcss-preset-env',
  ],
};

And here are the dependencies listed in my package.json:

"dependencies": {
    "date-fns": "^2.29.3",
    "next": "13.1.1",
    ...
  },
  "devDependencies": {
    "@fullhuman/postcss-purgecss": "^5.0.0",
    "@typescript-eslint/eslint-plugin": "5.48.0",
    ...
  }

In this project, I opt for global styles using SCSS over module styles. The main stylesheet, _app.tsx, looks like this:

import '../styles/Global.scss';
import type { AppProps } from 'next/app';

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

export default MyApp;

Let's say I have two CSS classes defined:

.bg-blue { background-color: blue; }
.bg-red { background-color: red; }

The issue arises when I switch from using bg-blue to bg-red in a div element's className; the new style doesn't reflect due to PurgeCSS seemingly not updating the stylesheet dynamically.

Although it's far from ideal, I'd be willing to disable the purge feature entirely if possible. Yet, I'm struggling to find the right approach to achieve this.

If anyone has any insights or suggestions on how to tackle this problem, please share them!

Answer №1

If you're searching for a solution to Next.js and PostCSS issues, I hope this explanation can assist you.

Dealing with Next.js 14, Panda-CSS, and PostCSS caused me to face a similar issue. However, I managed to resolve it by creating a custom script specifically for development purposes. This script is designed to monitor any modifications made to my .ts and .tsx files. Upon detecting a change, the script automatically updates my globals.css file (or in your case, styles/Global.scss).

This minor adjustment signals to Next.js that there have been style changes, prompting the framework to generate new CSS based on these alterations. This approach proved effective for me in maintaining up-to-date styles.

const chokidar = require("chokidar");
const fs = require("fs");
const path = require("path");

const cssFilePath = path.join(
  __dirname,
  "../../packages/app/src/app/globals.css"
);

function updateCssCounter() {
  let content = fs.readFileSync(cssFilePath, "utf8");
  let match = content.match(/\/\*\s*(\d+)\s*\*\//);
  let counter = match ? parseInt(match[1]) + 1 : 1;

  if (match) {
    content = content.replace(/\/\*\s*\d+\s*\*\//, `/* ${counter} */`);
  } else {
    content += `\n/* ${counter} */`;
  }

  fs.writeFileSync(cssFilePath, content, "utf8");
}

const watcher = chokidar.watch(
  [
    "../../packages/app/src/**/*.ts",
    "../../packages/app/src/**/*.tsx",
    "../../packages/design-system/src/**/*.ts",
    "../../packages/design-system/src/**/*.tsx",
  ],
  {
    ignored: /node_modules/,
    persistent: true,
  }
);

watcher.on("change", (path) => {
  console.log(`CHANGED: ${path}`);
  updateCssCounter();
});

console.log("Watching for file changes...");

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

Issue: React build script does not support conversion from 'BigInt' to 'number' error

After developing the UI using create-react-app, I encountered an issue. The UI works fine with the normal npm start command, but when I try to build it with npm run build, I get an error saying 'Conversion from 'BigInt' to 'number' ...

Modify CSS using Javascript by targeting the class of ".modalDialog > div {}"

I am currently working on a project that involves creating a Modal Layer using CSS. I have successfully implemented the modal layer, but now I need to figure out how to change the width from the default 400px to something else when I open it with Javascrip ...

What is the correct way to pass parameters when using the setState() function in React hooks?

I am working on a project where I have a list of country names. When a user clicks on one of the countries, I want to update the state with the name of the newly selected country. This state change will then trigger other changes in a useEffect(). The stat ...

What is the best way to create CSS rules that can be dynamically applied as classes using JavaScript?

I have been attempting to use the addClass function in JavaScript to add a class, but I am struggling to make it work. Is there a specific way to define a class that will be added to an element when clicked on? Here is what I have attempted: var input = ...

The behavior of the CSS Position property is exhibiting unique characteristics when used in

I am encountering an issue where an image is displaying differently based on the position attribute in Firefox compared to Chrome and IE11. Take a look at the preview on . Notice how the bottom tip of "Fountain Valley" is incorrectly positioned in Firefox ...

What could be the reason for box-shadows not appearing properly on Safari browsers?

Why are box shadows with decimals sometimes not displayed in Safari? Is there a solution to this issue? Here's an example of the code: div { width: 200px; height: 200px; box-shadow: 0px 0.0351725rem 0.0351725rem 0px, 0px 0px 0px 0.0175862re ...

Identify when a mouse hovers within 10 pixels of a div using jQuery

Is it possible to detect when a user hovers over a specific area within a div using JavaScript or jQuery, without adding any additional tags? -------------------------------- -------------------------------- -------------------------------- -------- ...

What is the best way to fetch all Firebase database IDs using Angular?

Is there a way to fetch all data from Firebase database along with their respective IDs? Currently, I have two functions - getAll() and get(input) that retrieve specific products based on the given ID. However, my current implementation only returns obje ...

The functionality of Intersection Observer causes text to appear over the header

Hey everyone, I've been working on a scrolling animation to make text appear when it's at least 50% visible. So far, I have an animated header with an Onscroll Event and Intersection Observer for the text. It's all working well, except for ...

Content in static JSON file failing to display in NextJS

I recently started using Next, and I've encountered an issue. There is a static JSON file located in the root of my project directory, structured as follows: {"data":[{"id":1,"attributes":{"name":"Test Prod ...

"Troubleshoot: Why is the Position Absolute Not Functioning in

Trying to achieve a layout similar to the last element at the bottom of the footer] 1, but getting something like this instead: https://i.sstatic.net/lXazk.png <footer> <div class="container-fluid"> <div class="row"> ...

WordPress site experiencing issues with sub-menus disappearing following recent upgrade

I'm currently investigating a problem on a WordPress website where sub-menus are not showing up after upgrading to WP 3.9.1. The website, which can be found here, is using the Zeus theme (v. 1.1.0) and it seems that the behavior of the sub-menus is co ...

I'm having trouble with jQuery recognizing the left-margin property. Is there a workaround for this issue?

I rarely use jquery, but I wanted to add animation to a side bar. The sidebar menu is 670px with a -670 left-margin. When the user hovers over it, I'd like the left-margin to change to 0px and reveal the hidden content. Upon mouseout, it should return ...

Creating a React component with a reference using TypeScript

Let's discuss a scenario with a reference: someReference; The someReference is essentially a React component structured like this: class SomeComponent<IProps> { getData = () => {}; render() { ...some content } } Now, how c ...

Switch out the content within a div upon selection

I'm currently working on a palette board project and facing some challenges when switching to a different theme. The initial page is set to have a Warm color palette, but I intend to alter this once the user clicks on the All theme option. Users wil ...

Prompt the user to take an action by opening a modal or dialogue box from a dropdown menu

I am looking to implement a functionality where a modal or dialogue will be opened when a user selects an option from a dropdown menu. As the dropdown menu will have multiple options, different dialogues/modals should appear based on the selected option. ...

Tips for setting up CSRF protection in a Next.js frontend application working in conjunction with a Spring Security backend application

I have been working on a project that utilizes Next.js for the frontend and Spring Boot for the server. I am currently implementing the user login/register feature. The core functionality is working, where a user can successfully send a post login request ...

What is the best way to incorporate multiple Bootstrap templates into an Angular project without causing conflicts between them?

When incorporating a bootstrap template into the admin interface, it is important to consider that its design may vary from the template used for visitors. Mixing multiple styles based on different templates can lead to conflicting styles and can potenti ...

Tips for efficiently updating state in React.js dynamically?

Is there a way to dynamically update the state of CurrentIndex whenever a user is selected? Currently, it is hardcoded to 0 but I would like to change that. I need the currentIndex to be updated whenever a user from the list is clicked. The SidePan ...

Header logo not showing up on webpage

While working on a website template for a friend, I encountered an issue when uploading the site. The logo image was displaying perfectly fine on my local drive, but once uploaded, it showed as a broken image icon on the live website. Here is the code sni ...