Change px to REM in Vue project

vue2.x

 npm i lib-flexible --save
   
Copy the code

Introduce lib-Flesible in main.js

import 'lib-flexible/flexible'
Copy the code
npm install px2rem-loader
Copy the code

Find util.js in the build file and add px2REm-loader to cssLoaders as follows:

Const cssLoader = {loader: 'CSS-loader ', options: {sourceMap: options.sourceMap}} // Add px2REm-loader to cssLoader. Saves 75 const px2remLoader = {loader: 'px2REm-loader ', options: {remUnit: 75}}Copy the code

Add px2remLoader in the generateLoaders method

function generateLoaders (loader, loaderOptions) { // const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] // const loaders = [cssLoader,px2remLoader] const loaders = options.usepostcss? [cssLoader, postcssLoader, px2remLoader] : [cssLoader, px2remLoader] if (loader) { loaders.push({ loader: loader + '-loader', options: Object.assign({}, loaderOptions, { sourceMap: options.sourceMap }) }) }Copy the code

vue3.x

NPM install postCSs-pxtorem --save-dev NPM install lib-flexible or yarn add lib-flexibleCopy the code

Let the web page according to device DPR and width, using viewport and HTML root element font size with REM to adapt to different sizes of mobile devices

In main.js introduction:

import 'lib-flexible/flexible.js'
Copy the code

Inside package.json, inside postcss add:

"postcss": { "plugins": { "autoprefixer": {}, "postcss-pxtorem": { "rootValue": 75, // 1/10 of the width of the design draft, (no comment is added to the JSON file, and the line comment and the downstream comment are deleted) "selectorBlackList": [" vant"],// Ignore rem "propList":["*"] // Attributes that need to be converted, such as' hight ', 'width', 'margin', etc., '*' indicates all}}}Copy the code

Restart the project when finished