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

modify the URL records within the GetJson function

My current address is "http://localhost:8000/index", and when I execute the following jQuery code: $.getJSON("1",function(data) { .....code }); It redirects to "http://localhost:8000/index/1". This works fine for now. ...

Deactivate tag Script using JQuery

Is there a way to dynamically remove two <script> tags from a page at the document ready event? Each tag is assigned its own unique id. I attempted to use the following code: $("#idPrimoScript").remove(); $("#idSecondoScript").remove(); However, t ...

Submitting form by double clicking and pressing enter at the same time

When using jQuery Validate to validate forms, I encounter a problem where double-clicking the submit button results in my application making two entries with the same data. This issue also occurs when pressing enter multiple times. Despite researching dif ...

The issue of the highlighted row not disappearing persists even after clicking on the adjacent table row

When selecting the gear icon for the menu option in a table row, I would like the background to turn yellow. I attempted the following code to highlight the table row: var view = Core.view.Menu.create({ model: model, menuContext: { ibmm: ibmm }, ...

Is it possible to relocate an iframe outside the body of a post in Blogger?

For my blog posts, I have a goal of relocating the first iframe used outside of the post body and into a custom div called #myvideos. Some blog templates, such as this example, have already achieved this by moving a video out of the post body. I would like ...

Directive's ng-click function fails to execute

This directive contains a function that should be executed when clicked. ebApp.directive('monthDir', function () { return { restrict: 'E', templateUrl: 'htmlFiles/monthDirective.html', transclu ...

Webpack is unable to locate a specific custom JavaScript file

Currently, we are in the process of transitioning from grunt to webpack for our project. Within our project, we have a JS file named boiler that is used to define the core classes which are frequently accessed. __boiler__.js define(function (require) { ...

Enhancing Website Functionality: How to Swap iFrame for DIV using PHP and AJAX

I am currently working on a website where I need to replace an iframe containing data stored in an invisible form with a div that updates its content using AJAX. If you don't want to read everything, skip to the end for my main question. The chall ...

Incorporate Calendly Script into your NextJs application

I'm currently working on integrating Calendly into my Next.js project. However, I am unsure about the process. My goal is to embed it on a specific page rather than in _app or _document. Here is what I have attempted so far: import Script from &apos ...

What is the best way to differentiate between a JSON object and a Waterline model instance?

Note: I have posted an issue regarding this on the Waterline repo, but unfortunately, I have not received a simpler solution than my current workaround. Within my User model, along with default attributes such as createdDate and modifiedDate, I also have ...

Concurrent Accordion and Color Transformation Animations

I am currently utilizing jQuery version 2.0.3 and jQuery UI version 1.10.3, specifically using the accordion feature. I am attempting to modify the color of the accordion panels as they open and close by implementing the following code: $(".main-content") ...

Locating a specific item using its individual ID within Firebase

One thing that's often overlooked in Firebase tutorials is how to retrieve objects based on their unique IDs. The push() method generates these unique IDs automatically, but the question remains: how do we access the specific object associated with an ...

Tips for allowing a position:absolute <div> to expand as though it were containing a lengthy <p>innerText

This div automatically adjusts its width to fit the content inside, even if it extends beyond the page boundaries. Is there a way to make this div expand to fill the entire width of the page without needing a paragraph? <div style="position:absolute;le ...

What is the best way to continuously monitor MongoDB for updates and sync them with my user interface?

Looking to continuously monitor a user's notifications in MongoDB, updating them on specific actions and displaying updates on my React frontend without reloading every time the user logs in. I am currently utilizing Node and Mongoose models for datab ...

Run the .map() method at regular intervals of 'x' seconds

I have a certain function in mind: function fetchDesign (items) { items.map(item => item.classList.add('selected')) // additional code here } Is there a way to trigger item.classList.add('selected') every 2 seconds, while ensu ...

Deactivate interactive functions on the mat-slider while preserving the CSS styling

I'm attempting to create a mat-slider with a thumb label that remains visible at all times. Below is my mat-slider component: <mat-slider class="example-margin" [disabled]="false" [thumbLabel]="true" [tickInterval]="tickInterval" ...

Is there a way to dynamically incorporate line numbers into Google Code Prettify?

Having some trouble with formatting code and inserting/removing line numbers dynamically. The line numbers appear on the first page load, but disappear after clicking run. They don't show at all on my website. I want to allow users to click a button a ...

Encountered an unhandled runtime error: TypeError - the function destroy is not recognized

While working with Next.js and attempting to create a component, I encountered an Unhandled Runtime Error stating "TypeError: destroy is not a function" when using useEffect. "use client" import { useEffect, useState} from "react"; exp ...

What is the best way to set up a server in React using Express or HTTP?

I am currently in the process of developing a web application using react js. In order to create a server for my client within the project, I have decided to utilize either express or http. Here is the code snippet that I attempted: import React from " ...

NodeJS Fork - React each instance a new line is detected from the child process

I am currently working on creating a NodeJS function (on Windows7) that listens to a subprocess and handles each newline sent through the subprocess in Node. The following example demonstrates this: var express = require('express'); var app = ex ...