Having trouble with the postcss-import grunt plugin?

Here is the layout of my project:

my_project
|-- css
|   -- main.css
|-- css-dev
|   -- main.css
|-- node_modules
|   -- bootstrap
|       -- dist
|           -- css
|               -- bootstrap.css
|-- package.json
`-- Gruntfile.js

The contents of my Gruntfile.js are as follows:

module.exports = function (grunt) {
    var processorArray = [
        require('postcss-import')(),
        require('cssnano')()
    ];
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        postcss: {
            options: {
                processors: processorArray
            },
            dist: {
                files: [{
                    expand: true,
                    cwd: 'css-dev/',
                    src: ['**/*.css'],
                    dest: 'css/'
                }]
            }
        },
        watch: {
            scripts: {
                files: ['css-dev/*.css'],
                tasks: ['postcss'],
                options: {
                    spawn: false
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-postcss');
    grunt.loadNpmTasks('grunt-contrib-watch');

};

My intention is to utilize the postcss-import Grunt plugin to import the bootstrap.css file into the css-dev/main.css, then minify it and place the final result in the css directory under the name main.css.

This is the content of the main.css file located in the css-dev directory:

@import "bootstrap.css";

/* normalize selectors */
h1::before, h1:before {
    /* reduce shorthand even further */
    margin: 10px 20px 10px 20px;
    /* reduce color values */
    color: #ff0000;
    /* drop outdated vendor prefixes */
    -webkit-border-radius: 16px;
    border-radius: 16px;
    /* remove duplicated properties */
    font-weight: normal;
    font-weight: normal;
    /* reduce position values */
    background-position: bottom right;
}

/* correct invalid placement */
@charset "utf-8";

.test{
    font: 12px Calibri;
}

Although everything seems to be set up correctly, after running the Grunt tasks, the @import does not seem to be working as expected. The resulting file looks like this:

@import "bootstrap.css";h1:before{margin:10px 20px;color:red;border-radius:16px;font-weight:400;background-position:100% 100%}.test{font:2px Calibri}

Unexpectedly, the content of the bootstrap file was not imported into the main.css file.

What could be causing this issue and how can I resolve it?

Answer №1

Your bootstrap css file may not be found by postcss-import. You can specify the exact location for it to look using the path property.

var processorArray = [
    require('postcss-import')({
        path: 'node_modules/bootstrap/dist/css'
    }),
    require('cssnano')()
];
grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    postcss: {
        options: {
            processors: processorArray
        },
        dist: {
            files: [{
                expand: true,
                cwd: 'css-dev/',
                src: ['**/*.css'],
                dest: 'css/'
            }]
        }
    },
    watch: {
        scripts: {
            files: ['css-dev/*.css'],
            tasks: ['postcss'],
            options: {
                spawn: false
            }
        }
    }
});

EDIT

The method of pulling your css libraries will determine how they are automatically found. According to the plugin's documentation:

This plugin can consume local files, node modules or web_modules. To resolve path of an @import rule, it can look into root directory (by default process.cwd()), web_modules, node_modules or local modules. When importing a module, it will looks for index.css or file referenced in package.json in the style or main fields. You can also provide manually multiples paths where to look at.

If you import your bootstrap css as

@import "bootstrap.css";

It will only search in these places automatically

web_modules/bootstrap.css
node_modules/bootstrap.css
local_modules/bootstrap.css

Changing your import to

@import "bootstrap";

Will prompt a search in these folders for index.css

web_modules/bootstrap/index.css
node_modules/bootstrap/index.css
local_modules/bootstrap/index.css

If you have used a package manager to get your css library and there is a package.json in its root folder

node_modules/bootstrap/package.json

The package.json can guide postcss on where to locate the library through the main or style property

{
    ...
    "main": "dist/css/bootstrap.css"
}

Ultimately, the method of pulling your libraries will affect how they are found. If you manually place them in nested folders beyond the plugin's automatic search range, you'll need to add the direct paths to the file in the path object as shown in my original response.

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 employed by the script to ascertain the value of n within the function(n)?

I've recently started learning about jQuery. I came across a program online that uses a function where the value of n starts from 0 and goes up to the total number of elements. In the example below, there is only one img element and jQuery targets thi ...

The "results per page" ajax dropdown in Yii stops working after other ajax content is loaded on the page

One of the views in Yii framework is the "Patients" view, which contains several CGridViews and other elements that are loaded via ajax after the initial view has loaded. Some of these elements are nested within multiple levels of ajax-loaded divs. Within ...

Hide a parent div in jQuery depending on the checkbox status

I have a code snippet that I need help with. You can view the code here. $("#filters :checkbox").change(function() { $(".listing-details > div").hide(); $("#filters :checkbox:checked").each(function() { $(".listing-details ." + $(this). ...

Crafting Effective AngularJS Directives

Recently, I've been delving into AngularJS and have grasped the core concepts quite well. As I embark on building my own application, I find myself struggling with laying out the blueprint, particularly in terms of directive design. Are there any not ...

The hover effect does not work when clicking the mouse button in the Chrome browser

All: [UPDATE] Another method I discovered to achieve this is not a solution, but rather a workaround: Utilize the mousedown event as a trigger (since a drag action is needed, a mousedown event is required), within that, attach a mouseover event to that sp ...

In the process of extracting information from a JSON response text

I'm having trouble extracting specific data from a JSON response. Here is an example of the response structure: { "status": "success", "reservations": [ { "id": "22959", "subject": "SubjectName1", "modifiedDate" ...

I'm working with Angular 12, Bootstrap 5, and ngPrime, and I'm looking to overlap a p-dialog with another element in my project

Is there a way in Angular 12 with Bootstrap 5 using ngPrime to overlap a p-dialog over any other element without using z-index and CSS, solely relying on PrimeNG? I have tried using z-index with: .my-class{ z-index: 2147483647 !important; } However, ...

Material UI drop down select position placement

Having an issue with the dropdown position when using select from material UI. It's not appearing in the correct location. Desired Dropdown Position: Current Dropdown Position: when opening the dropdown The dropdown is displaying in the center of ...

Is there a way to store a jQuery CSS manipulation within a cookie?

On my Wordpress site, I have a code that allows users to change the font size of the body when they click on one of three generated buttons: <button class='body_standard_font_size'>Standard</button> <button class='body_medium ...

Issue encountered in transmitting information from JSP to servlet

I am facing an issue with receiving data from JSP to servlet. I understand that I need to serialize this data using JSON. In my JSP, I have written the following JavaScript code: var myJSONText = JSON.stringify(items); document.getElementById('test&a ...

Master your code with Rxjs optimization

Looking at a block of code: if (this.organization) { this.orgService.updateOrganization(this.createOrganizationForm.value).subscribe(() => { this.alertify.success(`Organization ${this.organization.name} was updated`); this.dialogRef.close(true ...

Does the height of a block element change based on the font size?

Does the font size of content affect the height of a block element? Let me demonstrate what I'm talking about, take a look at this example fiddle If you enlarge the font size of the class .p within the div, you'll notice that the div's hei ...

Converting JavaScript code for Angular: A step-by-step guide

I have been working on integrating a feature similar to the one demonstrated in this Angular project: https://codepen.io/vincentorback/pen/NGXjda While the code compiles without any issues in VS code, I encountered two errors when attempting to preview it ...

What's the reason for the inability to resize fieldset using both?

Can someone explain why the resize control is not enabled on the fieldset element? The documentation mentions that resize does not work with: Inline elements Block elements that have overflow set to visible fieldset { resize: both; overflow: h ...

implement css styling to grid view upon clicking

I have been attempting to add a background color to a grid view row when clicked on that specific row. <script type="text/javascript"> function ChangeRowColor(objref) { objref.style.backgroundcolor = "red"; } </sc ...

What is the process for uploading a single file and an array of files with varying names using multer?

I am having trouble figuring out how to upload a main image and side images from 2 different file inputs using multer. It seems that multer only accepts one upload per route. How can I work around this issue? I keep getting an unexpected field error when a ...

Utilize the input type=date value in the date function to obtain a specific format

How can I pass the value of input type=date to a JavaScript date function? In my HTML code, I have used: <input type=date ng-model="dueDate"> <input type="time" ng-model="dueTime"> <button class="button button-block" ng-click="upload_dueda ...

What methods and technologies are accessible for executing JavaScript through PHP?

Are there any frameworks or tools available to execute JavaScript from PHP? Is there a similar project like the Harmony project for PHP? I am interested in running JS unit tests (or even BDD) directly from PHP, as demonstrated in this post (for Ruby). Am ...

Exploring the implementation of window.addEventListener within an Angular project

I am currently working on testing a method in Angular using Jasmine. However, I am running into an issue with triggering the mouse event (specifically when the browser back button is clicked). Below is the code snippet I'm working with: navigate() { ...

`how to insert finished HTML & CSS header into WordPress PHP documents`

After dedicating countless hours to studying, I still can't figure out how Wordpress will locate and utilize my alternate header. The code snippet below served as a helpful starting point: <!--?php /* */ if(is_page(23)) { get_header('about&a ...