What is the best way to utilize purgeCss in conjunction with other module exports?

After reading the documentation, I want to integrate purgeCss into my NextJS project. The recommended configuration in the docs suggests updating the next.config.js file like this:

module.exports = withCss(withPurgeCss())

However, I am unsure where exactly I should apply my current configuration settings.

module.exports = {
    distDir: '../.next',
    webpack: config => {
        const env = Object.keys(process.env).reduce((acc, curr) => {
            acc[`process.env.${curr}`] = JSON.stringify(process.env[curr]);
            return acc;
        }, {});

        config.resolve.modules.push(path.resolve('./'));
        config.plugins.push(new webpack.DefinePlugin(env));

        return config;
    },
};

As for my postcss.config.js:

module.exports = {
    "plugins": [
        "postcss-flexbugs-fixes",
        [
            "postcss-preset-env",
            {
                "autoprefixer": {
                    "flexbox": "no-2009"
                },
                "stage": 3,
                "features": {
                    "custom-properties": false
                }
            }
        ],
        [
            '@fullhuman/postcss-purgecss',
            {
                content: [
                    './pages/**/*.{js,jsx,ts,tsx}',
                    './components/**/*.{js,jsx,ts,tsx}'
                ],
                defaultExtractor: content => content.match(/[\w-/:]+(?<!:/)/g) || [],
                safelist: ["html", "body"]
            }
        ],
    ]
}

Answer №1

Remember to place your config object inside the innermost plugin call for proper setup.

// next.config.js

module.exports = withCss(withPurgeCss({
    distDir: '../.next',
    webpack: config => {
        const env = Object.keys(process.env).reduce((acc, curr) => {
            acc[`process.env.${curr}`] = JSON.stringify(process.env[curr]);
            return acc;
        }, {});

        config.resolve.modules.push(path.resolve('./'));
        config.plugins.push(new webpack.DefinePlugin(env));

        return config;
    },
}))

If you encounter issues with the postcss.config.js, refer to the object-based format recommended in the Next.js documentation (found at the bottom of the page):

module.exports = {
    'plugins': {
        'postcss-flexbugs-fixes': {},
        'postcss-preset-env': {
            'autoprefixer': {
                'flexbox': "no-2009"
            },
            'stage': 3,
            'features': {
                'custom-properties': false
            }
        },
        '@fullhuman/postcss-purgecss': {
            'content': [
                './pages/**/*.{js,jsx,ts,tsx}',
                './components/**/*.{js,jsx,ts,tsx}'
            ],
            'defaultExtractor': content => content.match(/[\w-/:]+(?<!:)\/g) || [],
            'safelist': ['html', 'body']
        },
    }
}

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

Implementing a Tab on Firefox Extension Upon Window Load

I have a requirement to add a tab whenever a new Firefox window is loaded for my bootstrap extension. Below is the code snippet I am using: var WindowListener = { setupBrowserUI: function(window) { window.gBrowser.selectedTab=window.gBrowser.a ...

Choose an image and save the selection information for the following page (Tarot card)

I'm in the process of creating a website that showcases multiple tarot cards. The goal is for users to select the cards they're interested in and have their chosen card displayed on the next page. I've implemented some code for selecting the ...

Exploring ways to validate the existence of a class in HTML table elements

If I want to verify if each element has a specific class when creating tables and clicking on the corresponding cells above them, This is what I have tried. However, it did not work as expected. How can I make this work correctly? What am I missing her ...

Utilize CountUp.js to generate a dynamic timer for tracking days and hours

I am looking to create a unique counter similar to the one featured on this website https://inorganik.github.io/countUp.js/ that counts up to a specific number representing hours. My goal is to display it in a format such as 3d13h, indicating days and hour ...

Web Scraping ASU Courses using Node.js

I'm a beginner when it comes to Node.js, so please forgive me if I sound confused. Currently, I am attempting to scrape course information from ASU's course catalog (https://webapp4.asu.edu/catalog/) using tools like Zombie, Node.IO, and the HTT ...

When accessing nested objects in Props in Vue.js, an error may occur if the property of null/undefined

When I make an axios call, I receive an object which I pass to a child component. However, when I attempt to loop through the object in the child component to access a property of another nested object, I encounter an issue where the property is showing as ...

Chaining promises allows you to utilize the outcome of one request to make another

I've been experimenting with ES6 in node.js and want to transition from using callbacks to promises. I created a test project to fetch an oauth2 token from an api/endpoint, refresh it, and then revoke it. My code snippet is as follows: const oauth2Ad ...

Retry request with an AngularJS interceptor

Currently, I am in the process of developing an Angular application and encountering some challenges while implementing a retry mechanism for the latest request within an HTTP interceptor. The interceptor is primarily used for authentication validation on ...

I am having trouble getting the Audio Code (a very basic code) to function properly

<audio id="myAudio" src="Avengers.mp3" type="audio/mpeg"></audio> <script> window.onload = function(){ document.getElementById('myAudio').play() } </script> Recently experimenting with some code in NotePad, a friend had ...

Keep the division visible once the form has been successfully submitted

Initially, I have created 3 divs that are controlled using input type buttons. These buttons serve the purpose of displaying and hiding the hidden divs. Within these divs, there are forms to store data. Currently, my goal is to ensure that the div that was ...

Vue.js is encountering an issue with receiving the accurate return value from a POST function

I am facing an issue where I am unable to receive the full data that is being sent from the frontend to the backend. Here is an example of the data structure that I am sending: { _id: 64a8a8e9903039edb52ccc4c, productName: 'Vial 2ml(US) Type1&apos ...

When exporting an enum in StencilJS with TypeScript, the error "Cannot find name..." may occur

Looking for a solution: https://github.com/napolev/stencil-cannot-find-name In this project, there are two main files to consider: custom-container.tsx import { Component, Element, State } from '@stencil/core'; @Component({ tag: 'cu ...

Utilize express.static to showcase and fetch HTML content before serving JavaScript files

I'm having trouble getting my home.html file to display properly on the browser when I'm using express.static. Here is how my directory and file layout are structured: dir main -server.js dir subMain dir routing -routes.js ...

Utilizing the useState hook to manage state

Is there a way to fetch the useState from another file in order to export sliderCount? Your assistance is greatly appreciated. I have two files. The first file utilizes the useState function and modifies the state upon button click. In the second file, I ...

Different techniques to access values in a JSON array without relying on specific index positions

After making a request to an API, I received a JSON array with various attributes. One of the attributes is "State" and my task is to extract all the "EventName"(s) where State: "PR". The user will select the state from a dropdown menu. In order to achiev ...

What is the significance of :: in AngularJS?

When reviewing certain Angular JS files, I often come across the following syntax. What is the significance of a double colon "::" in this context? <span>{{::x}}</span> <div>{{::y.z()}}</div> ...

I am facing an issue with submitting a form using jQuery POST and php serialization

I am struggling to send form data using jQuery. The data seems to be stuck in a loop where it keeps requesting the page ./?page=game&mode=search&type=private with the GET function and does not reach the server. Can someone help me identify what I m ...

Is there a way to extract information from an external XML document and incorporate it into an HTML file?

I am attempting to extract information from an XML file that is not stored on my website's server. My goal is to utilize this data for various purposes, such as generating charts. One specific example involves using weather data from an XML file locat ...

Tips for verifying the inclusion of the + symbol in the country code in Angular 7

My form includes a text box where users can input a country code preceded by a + sign. If a user enters only numbers, we need to restrict that action and prompt them to enter the country code with a + sign, for example: +91, +230, ... I've been tryin ...

Having trouble locating an element on a webpage? When inspecting the element, are you noticing that the HTML code differs from the source page?

I'm having trouble locating a specific element on a webpage. When I use the Inspect Element tool, I can see the HTML code with the element id = username, but when I check the page source, all I see is JavaScript code. Does anyone have any suggestions ...