Automatic conversion of px to rem in vue

Posted by needphphelp on Wed, 09 Mar 2022 02:06:14 +0100

If rem is often used in the project, set the font size of the root node html automatically. Because the REM unit is relative to the font size of the root node, the size of REM can be changed dynamically by setting the font size of the root node. But px is common. What good method can automatically convert it into REM. The answer is yes.

  • Vue cli: create a project using scaffolding tools.
  • Postcss pxtorem: a plug-in that converts px to rem.

1. Create rem.js file

Many people will habitually add closures when writing such gadget files, which is actually unnecessary. Each file in ES6 is a separate module.

/***1,Create rem.js file
 **Many people will habitually add closures when writing such gadget files, which is actually unnecessary. Each file in ES6 is a separate module.
 **/

/**General:
 *The design drawing of mobile terminal is 750px, basesize = 32, scale = document documentElement. clientWidth / 750;
 *pc The end design drawing is 1920px, basesize = 16, scale = document documentElement. clientWidth / 1920;
 **/
// Base size
const baseSize = 16;

// Set rem function
function setRem() {
  // The scale of the current page width relative to 750 width can be modified according to your needs.
  const scale = document.documentElement.clientWidth / 1920;
  var autoWidth = Math.round(baseSize * Math.min(scale, 2));
  // Set the minimum font of the page
  if (autoWidth < 10) {
    autoWidth = 10;
  }
  // Set the font size of the page root node
  document.documentElement.style.fontSize = autoWidth + "px";
}

// initialization
setRem();

// Reset rem when changing window size
window.onresize = function () {
  setRem();
};

2. In main Introducing rem.js into JS

The path of rem.js is set by yourself. Write that path wherever you go. After importing a file, check whether the html node of the page is automatically added with font size.

import "./utils/rem";

Note: when this step is completed, that is, the rem layout is realized. During the actual development, we still need to calculate the corresponding rem value to develop. Next, we will configure webpack and automatically convert px to the corresponding rem value.

3. Configure postcss pxtorem to automatically convert px to rem

1. Install postcss pxtorem

$ npm install postcss-pxtorem --save-dev
//npm install postcss-pxtorem -D

2. Configuration file

1>vue-cli2. Modify the root directory postcssrc. X JS file

Locate postcssrc. In the root directory JS file and find the plugins attribute in it. Add the setting of pxtorem.

"plugins": {
  "postcss-pxtorem": {
  "rootValue": 32,
  "unitPrecision": 2, //Keep decimal places
  "propList": ["*"],
  // Note: if a third-party UI such as VUX is used, it needs to be configured to ignore the selector without conversion.
  // The rule is the string contained in the class. For example, all class prefixes in vux are weui -. It can also be regular.
  "selectorBlackList": ["weui-"],//Filtered class name
  "minPixelValue":2 //All values less than the setting are not converted
    }
}

2>vue-cli3. X and vue-cli4 X modify the root directory Vue config. JS file

css: {
    // css preset configuration item
    loaderOptions: {
      postcss: {
        plugins: [
          require('postcss-pxtorem')({
            rootValue: 16, // Base of conversion
            unitPrecision:2,//Keep decimal places
            selectorBlackList: ['.wu'], // Ignore transform regular matches
            propList: ['*'],
            minPixelValue: 2
          })
        ]
      }
    }
  },

####

3. Normal use px after restart

According to the above configuration items, px unit can be directly used in development.

For example, the design drawing given by the design is * * 750_ 1136_, Then you can write it directly in the page

body {
  width: 750px;
  height: 1136px;
}

Will be converted to

body {
  widht: 23.4375rem;
  height: 35.5rem;
}

Note: this method supports * * import * * * and ` vue ` single file ` style '. The use of ` @ import url() in 'style' is not supported at the moment*` \\

4. Convert px in Vue into rem plug-in

1> Comparison of three common plug-ins

Official document of postcss plugin px2rem: https://www.npmjs.com/package/postcss-plugin-px2rem Official documents of postcss pxtorem: https://www.npmjs.com/package/postcss-pxtorem postcss-px2rem official document: https://www.npmjs.com/package/postcss-px2rem

2> Installation

//Install postcss-plugin-px2rem
npm i postcss-plugin-px2rem  --save-dev

//Postcss postcsm installation
npm i postcss-pxtorem  --save-dev

//Install postcss-px2rem
npm install postcss-px2rem --save-dev

####

3> Configuration file

In vue-cli3 X. if you don't want to convert PX in some places. You can simply use uppercase PX or px. Configuration of postcss plugin px2rem

 css: {
   loaderOptions: {
     postcss: {
       plugins: [
          require('postcss-plugin-px2rem')({
             // rootValue: 100, / / the conversion base is 100 by default. In this case, set the font of the root label as 1rem and 50px, so that you can measure how many Pxs from the design and write more PX directly in the code.
             // unitPrecision: 5, / / allows REM units to grow to decimal digits.
             /propWhiteList: [],  //The default value is an empty array, which means that the whitelist is disabled and all properties are enabled.
             // propBlackList: [], / / blacklist
             exclude: /(node_module)/,  //The default is false. You can (reg) use regular expressions to exclude some folders, such as / (node_module) /. If you want to convert px in the front-end UI framework into rem, please set this property as the default value
             selectorBlackList: [], //Selector to ignore and keep as px
             // ignoreIdentifier: false, / / (boolean/string) method that ignores a single attribute. When ignoreidentifier is enabled, replace will be automatically set to true.
             // replace: true, / / (Boolean value) replace the rule containing REM instead of adding fallback.
             mediaQuery: false,  //(Boolean) allows conversion of px in media queries.
             minPixelValue: 3 //Set the minimum pixel value to replace (3px will be converted to rem). Default 0
          }),
        ]
     }
         }
 },

Configuration of postcss pxtorem

 css: {
        loaderOptions: {
            postcss: {
                plugins: [
                    require('postcss-pxtorem')({//Here is the configuration item. See the official document for details
                        rootValue : 1, // Base of conversion
                        selectorBlackList  : ['weui','mu'], // Ignore transform regular matches
                        propList   : ['*'],
                    }),
                ]
            }
        }
    },

Configuration of postcss px2rem

css: {
        loaderOptions: {
          postcss: {
                plugins: [
                    require('postcss-px2rem')({ //See the official document for configuration items
                        remUnit: 30
                    }), // Base of conversion
                ]
            }
        }
    },