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

Manually incorporating multiple React components into a single container

I am currently in the process of upgrading an old JavaScript application that relies heavily on jQuery by introducing some React components. The existing code utilizes JS/jQuery to dynamically add elements to the DOM, and I am looking for a way to replace ...

What is the best way to organize class usage within other classes to prevent circular dependencies?

The engine class presented below utilizes two renderer classes that extend a base renderer class: import {RendererOne} from "./renderer-one"; import {RendererTwo} from "./renderer-two"; export class Engine { coordinates: number; randomProperty: ...

Is there a way for me to store the message I sent using discord.js in a variable?

I'm looking to send a message in the channel and then react to it by getting that message for a message reaction. bot.sendMessage({ to: channelID, message: '@everyone\n' + message.slice(16) + '\n\nThis message is a ...

The presence of fs.existsSync as a function is not recognized when importing electron

I am currently developing a Vue and Electron application and I encountered a problem while trying to restart the application. Here is my code snippet: import { app } from 'electron'; export default { name: 'Home', methods: { re ...

Steps to gather all the images within a directory

Take a look at this demo When you click on the "next" button, new images are loaded from the internet. In my application, all the images are stored in the img/image folder with names like 1.jpg, hi.png, etc. My question is, how can I display these image ...

The action 'addSection' is restricted to private access and can only be utilized internally by the class named 'File'

const versionList = Object.keys(releaseNote) for (const key of versionList) { // Skip a version if none of its release notes are chosen for cherry-picking. const shouldInclude = cherryPick[key].some(Boolean) if (!shouldInclude) { continue } // Include vers ...

Traversing through pair of arrays simultaneously using forEach loop in JavaScript

I am trying to create a for loop that simultaneously iterates through two variables. One is an array named n, and the other, j, ranges from 0 to 16. var n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22]; var m = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; ...

Encountering an issue with the removal of slides when updating JSON data for angular-flexslider

Issue: Although my JSON object is updating, the slider does not update for all resorts as expected. Sometimes it fails to update when the JSON object changes. The resorts (image collections) that do not update are throwing an error stating "cannot read pr ...

Is there a way to acquire and set up a JS-file (excluding NPM package) directly through an NPM URL?

Is it feasible to include the URL for the "checkout.js" JavaScript file in the package.json file, rather than directly adding it to the Index.html? Please note that this is a standalone JavaScript file and not an NPM package. The purpose behind this appr ...

Is there a way to prevent the text in my text boxes from staying there when I refresh the page?

Currently working on an HTML5 project with Javascript, here is a snippet of my code: Your inquiry <textarea type="text" name="phrase" id="phrase" cols="50" rows="5" placeholder="Write your text here. . ."></textarea> I am looking for a way ...

Discovering a device's model using JavaScript

How can I use Javascript to redirect users to different download pages based on their device model? ...

Having trouble deciphering the JSON data structure in JavaScript

How can values be passed back to a form that was submitted to the server using Ajax? In this view (shown below), a simple data structure is returned for testing purposes: def detail(request, widget_id): widget = get_object_or_404(Widget, pk=widget_i ...

Using jQuery and Perl to create a dynamic progress bar that is based on the current state of a "pipeline file" and utilizes AJAX

I'm looking to create a small pipeline that enables users to select a file and run multiple scripts using it as an input. Some of these scripts may take several minutes to complete (time depends on the file's size), so I want to display a progres ...

When an array object is modified in Vue, it will automatically trigger the get method to validate any

One of the challenges I am facing is related to a button component that has a specific structure: <template> <button class="o-chip border-radius" :class="{ 'background-color-blue': theValue.isSelected, ...

Ajax/PHP - unrecognized value in autofill

I have implemented this particular example to execute an ajax data query from a MySQL database, which returns a table. Currently, this setup functions correctly when text is manually entered into the input form. Example: The issue arises with the autocom ...

The size of your request header section is too large and has exceeded the allowable limit

We have implemented AWS Amplify for our NextJS web application and are encountering errors only when attempting to load the deployed version on Amplify. Interestingly, there are no issues when running the app locally. https://i.stack.imgur.com/TacWk.png ...

Transforming an Angular 11 HTML template into Angular code

After attempting to transfer the Porto Admin HTML template to Angular, I encountered some issues. When including the CSS and JS dependencies in the project, everything worked fine with all the HTML code in index.html. However, when I moved the code to app. ...

AngularJS: default option not being selected in dropdown menus

I need assistance with a dropdown list issue. See the code snippet below: My Controller (function(angular) { 'use strict'; angular.module('ngrepeatSelect', []) .controller('ExampleController', ['$scope', functi ...

The issue I'm facing with my webpack-build is the exclusive appearance of the "error" that

Hey everyone! I'm currently facing an issue with importing a module called _module_name_ into my React project, specifically a TypeScript project named react-app. The module was actually developed by me and it's published on npm. When trying to i ...

Building a React Typescript service with axios functionality

When creating a service and calling it from the required functional component, there are two different approaches you can take. 1. export const userProfileService = { ResetPassword: async (userId: string) => { var response = await http.get ...