"PxToRem: A handy PostCSS plugin for converting pixel units

As a beginner in the world of Node.js and post processors for CSS, I recently took the time to install the following tools after going through multiple articles:

  1. Node.js (including npm)
  2. Gulp
  3. PostCSS
  4. Pxtorem (a PostCSS plugin for Gulp)

My goal is to utilize the 'pxtorem' plugin to convert my pixel units to rems for various CSS properties like font-size, margin, padding, border, width, height, etc. and generate a new CSS stylesheet with these changes.

Query: What specific commands should be included in my gulpfile.js to achieve this functionality?

To clarify, I'm still novice when it comes to defining variables and dependencies, relying on video tutorials and blog guides which lack the precise instructions for converting pixels to rems using PostCSS plugins.

This snippet showcases the content of my current gulpfile.js:

var gulp = require('gulp');
var postcss = require('gulp-postcss');
var pxtorem = require('gulp-pxtorem');

gulp.task('css', function() {
gulp.src('./css-1/*.css')
    .pipe(pxtorem())
    .pipe(gulp.dest('./dest'));
});

The mentioned code essentially copies my "styles-1.css" file from the "css-1" directory to the "dest" folder. While I crafted this script based on an article for understanding PostCSS, it lacks the correct configuration for pixel to rem conversion.

P.S. Operating on Windows 10 O/S currently.

Answer №1

According to the details on gulp-pxtorem, it mentions:

Choices

You need to input two sets of options. The first one is for postcss-pxtorem options...

Upon reviewing the information on postcss-pxtorem, I discovered that the configuration appears as follows:

{
    rootValue: 16,
    unitPrecision: 5,
    propWhiteList: ['font', 'font-size', 'line-height', 'letter-spacing'],
    selectorBlackList: [],
    replace: true,
    mediaQuery: false,
    minPixelValue: 0
}

This seems pretty straightforward, but you can refer to the documentation for a more detailed explanation of each option. The key option you should focus on is propWhiteList.

In your gulpfile:

var gulp = require('gulp');
var postcss = require('gulp-postcss');
var pxtorem = require('gulp-pxtorem');

gulp.task('css', function() {
    var opts = {
        propWhiteList: [
          'font-size',
          'margin',
          'padding',
          'border',
          'width',
          'height',
          ...etc
        ] 
    };
    gulp.src('./css-1/*.css')
        .pipe(pxtorem(opts))
        .pipe(gulp.dest('./dest'));
});

I don't think you need to utilize the second option to achieve your desired outcome.

Best of luck and happy coding!

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

Troubleshooting Node app on AWS with Docker exit status 1

I've been running a beta app on AWS with Express.js, Node, mongoose, and docker. With less than 10 daily active users, mainly friends helping test it out, the app seems to go down almost every day. At first, I suspected an issue with AWS itself, so I ...

What is the functionality of {all: initial} and how does it address issues with default values?

Why do paragraphs inherit properties like line-height and text-align from the div element? If values for these properties are: normal -> for line-height [i.e. font-size = 16px (initial / default value) * normal (value is usually around 1.2 -> 19.2 ...

What is the best way to display form fields that contain errors on the page?

Encountering a common issue of creating and editing form data. I have a complex form that is supposed to display all fields for validation purposes, but it's not working as expected. To clarify my problem, I've prepared a simple example. In this ...

Tips for sorting through various elements or items

How can I improve my filtering function to select multiple items simultaneously, such as fruits and animals, or even 3+ items? Currently, it only allows selecting one item at a time. I attempted using , but it had bugs that displayed the text incorrectly. ...

Next.js project encountered a TypeError with message [ERR_INVALID_ARG_TYPE]: The "to" argument is expected to be a string type

While working on a Next.js application, I came across a TypeError that is linked to the undefined "to" argument. This issue pops up when I launch my development server using npm run dev. Despite checking my environment setup and project dependencies, I hav ...

Guide on effectively incorporating res.render() within Mongoose's Model.find()?

Attempting to display Mongoose models within a Handlebars each loop has proven to be challenging. Despite trying to call res.render() within the find query, the page fails to load and ultimately results in an ERR_EMPTY_RESPONSE. As a newcomer to Mongoose ...

Encountering an issue when running npm build on server

I attempted to deploy my application on the hosting server and encountered the following error: Failed to compile. ./node_modules/next/dist/pages/_app.js Error: failed to process The global thread pool has not been initialized.: ThreadPoolBuildError { kin ...

Utilizing Bootstrap 5: Breaking a Page into Two Separate Vertical Sections

I am looking to design a unique grid system that divides the page into either 2 columns or 2 rows that are completely separate from each other. This means that the content on one side of the page does not expand to match the height of the content on the ot ...

When the @change event is triggered, Vue data objects do not exhibit reactivity

Trying to figure out why the msg and show data parameters are not updating when triggered by @change. To ensure that these parameters are only updated upon successful file upload, I placed them inside the lambda function of onload: reader.onload = functio ...

Utilize background-size:cover and incorporate text in a horizontally scrolling webpage

Struggling to create a minimalist HTML layout with a horizontal scrollbar, featuring a large image on the left and a lengthy text with columns on the right? I suspect the issue lies in the implementation of position:relative with float, as well as position ...

Convert HTML Form to PDF or Docx with Angular 4

My current setup involves Angular 4 with Node and MySQL. I have a form that, upon submission, needs to trigger a Save As... dialog box for the user to save the entered form contents as either a PDF or Word Doc. I've attempted using htmlDox and saveAs ...

Utilizing Express.js and AJAX to transfer JSON data from the server to the client

Having trouble sending JSON from Express.js back to the client, and I can't seem to figure out what's going wrong. routes/editor.js exports.save = function(req, res){ fs.readFile(__dirname + "/../public/index.html", function (err, data) { ...

Creating dynamic div elements using jQuery

I used a foreach loop in jQuery to create some divs. Everything seems to be working fine, but for some reason, my divs are missing SOME class properties. Here is the code snippet I am using: $("#item-container").append("<div class=\"panel col-md-2 ...

The integration of CSS into Laravel was unsuccessful

Below is the content of my index file located in views.admin: <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet&qu ...

Unable to locate socket.io for client if server is created without a handler

Issue with locating socket.io.js file for client: <script src="/socket.io/socket.io.js"></script> Error occurs when server is created without a handler function: var app = require('http').createServer(handler) , io = require(&apo ...

unable to retrieve information from the redis cache

Attempting to retrieve data from cache using the readData function in the controller file. Encountering an issue where the someVal variable is initially undefined after calling readData, but eventually gets populated with data after receiving a callback ...

How can we create a flexible item that can be resized along with another item set to a fixed length?

Is there a way to create an element with a fixed height and width of 40px, while having another element next to it that takes up the remaining space of the parent element's width? I want the second element to shrink when resizing, while the first one ...

Node.js: Can we include global-like variables in a required module similar to __dirname and __filename?

One interesting approach is to override the wrap method of a module and introduce a global variable called 'myVar': var Module = require("module"); (function() { Module.wrap = function(script) { var wrapper = [ '(function (expor ...

Verify the string to see if it contains a Steam game key

I am seeking assistance with a task that involves verifying whether a specific string contains a particular pattern: Below are several strings in an array: [ "please use this key: ')D9ad-98ada-jiada-8a8aa'", "kK8AD-AODK8-ADA7A", "heres a fr ...

Creating Functional Tabs Using CSS and JavaScript

I've been experimenting with this code snippet, trying to get it to work better. It's still a work in progress as I'm new to this and have only customized it for my phone so far. The issue can be seen by clicking on the Projects and Today ta ...